NGINX Catch All Subdomain


nginx catch all subdomain

NGINX will serve all the subdomains that you have configure in its server config file. However, what about subdomains not listed on your server config? The solution is to simply create a catch all subdomain to handle all subdomains not listed in your NGINX server config file. It also works if your clients ask you for a separate subdomain for each of them. Let us take a look at how to configure NGINX catch all subdomain for your website/application.

 

How to Configure NGINX Catch All Subdomain

Here are the steps to configure NGINX catch all subdomain for your website.

 

1. Open NGINX config file

Open NGINX config file in a text editor. You will find NGINX config file at one of the following locations, depending on the type of installation


/etc/nginx/conf.d/default.conf
/etc/nginx/sites-enabled/default
/etc/nginx/nginx.conf

$ sudo vim /etc/nginx/nginx.conf

 

2. Setup NGINX Catch All Subdomain

Let’s say you have a domain www.example.com and want a catchall subdomain to handle subdomains on your websites. Then create a separate Server context for your wildcard subdomain, as shown in bold. For example,


server {
 server_name example.com www.example.com;
 root www/html;
}

server {
 server_name ~^(.*)\.example\.com$ ;
 root www/html/$1;
}

 

In the above code, the first server block will serve your usual URLs from www.example.com as well as example.com while the second server block will handle requests to all other sub domains such as blog.example.com, api.example.com, app.example.com, etc.

 

 

If you want to run a couple of specific subdomains and also keep a catch all subdomain, then place the specific subdomains (e.g blog, app, etc) above the wildcard subdomains, as shown below.

 


server {
 server_name example.com www.example.com;
 root www/html;
}
server {
 server_name blog.example.com;
 root www/html/blog;
}
server {
 server_name app.example.com;
 root www/html/app;
}

server {
 server_name ~^(.*)\.example\.com$ ;
 root www/html/$1;
}

 

Now, NGINX will handle all requests to blog.example.com using 2nd server block and the ones to app.example.com using the 3rd server block. All other subdomains will be handled by the wildcard subdomain.

 

3. Reload NGINX web server

Test the config file to ensure there are no errors.

$ sudo nginx -t

 

If you get no error message, reload NGINX server to apply changes.

$ sudo service nginx reload

 

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!