How to Setup VirtualHost for Wildcard Subdomain in NGINX

setup virtualhost wildcard subdomain nginx

Sometimes, you may need to use wildcard subdomains for your website, like in case you need to create separate subdomains for each client & customer. Here’s how to setup virtualhost for wildcard subdomain in NGINX.


How to Setup VirtualHost for Wildcard Subdomain in NGINX

Here are the steps to setup Virtualhost for wildcard subdomain in NGINX.


1. Open NGINX Config File

Open NGINX config file in a text editor. You will typically find it at /etc/nginx/nginx.conf

$ sudo vim /etc/nginx/nginx.conf


2. Add Virtual Host for wildcard subdomains

Create a separate Server context for your wildcard subdomain. For example,

server {
 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 as well as while the second server block will handle requests to all other sub domains such as,,, etc.


3. Reload NGINX web server

Reload NGINX server to apply changes.

$ sudo service nginx reload


That’s it! Now NGINX will serve your usual domains (, using the 1st server block and other subdomains(e.g, using the 2nd 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!