How to Use ServerName Wildcards in NGINX


servername wildcards in NGINX

Sometimes, you might need to host many subdomains on the same IP or server. For example, you might have to create a separate subdomain for each client/customer because it is their requirement. In such case, it can be tedious to setup separate virtual hosts for each subdomain. In that case, you can use wildcard characters in your servername to ensure that all your subdomains resolve to the same virtual host. Let us take a look at how to use servername wildcards in NGINX.

 

How to Use ServerName Wildcards in NGINX

Here are the steps to use servername wildcards in NGINX.

 

1. Open NGINX config file

Open NGINX config file in a text editor.

You will find it 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. Use Servername Wildcards

Let’s say your website is hosted at www.domain.com hosted at /var/www/site and you want to create separate subdomains/portals for your clients client1.domain.com, client2.domain.com, etc. all of which resolve to same site but hosted at /var/www/site/client1, /var/www/site/client2, etc respectively. In that case, create a separate server block to serve all the subdomains, as shown in bold

server {
  server_name domain.com www.domain.com;
  root /var/www/site;
}

server {
  server_name ~^(.*)\.domain\.com$ ;
  root /var/www/site/$1;
}

 

For some reason, if the above configuration doesn’t work for you, you try the following config for wildcard servernames.

server {
  listen 80;
  listen [::]:80;

  server_name ~^(?<subdomain>[^.]+).domain.com;

  root /var/www/site/$subdomain;

  access_log /var/log/nginx/$host-access.log;
  error_log  /var/log/nginx/$host-error.log;
}

 

The above config will match everything except dot in $subdomain variable. For example, it will match test1.wildcard.com, test1-demo.wildcard.com, etc.

 

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

 

That’s it! Now when users request www.domain.com it will be served by your first server block, whereas when they serve request client1.domain.com, client2.domain.com, etc they will be served by your second server block.

 

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!