setup catch-all subdomains in nginx

How to Setup Catch-All Subdomains in NGINX

Sometimes you may need to setup wildcard subdomains in NGINX. In this article, we will look at how to configure catch-all subdomains in NGINX so that all requests sent to your domain, irrespective of the requested subdomain, are properly handled by your server.


How to Setup Catch-All Subdomains in NGINX

Here are the steps to setup catch-all subdomains in NGINX.


1. Update NGINX Configuration

Open NGINX configuration file in a text editor.

$ sudo vi /etc/nginx/nginx.conf


2. Setup Catch-all subdomains

Let us say you want to configure wildcard subdomains for your website example.com. In this case, add the following line to your NGINX configuration file.

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

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

In the above server configuration, we have created two server blocks. The first one listens to example.com and www.example.com. The second one listens to other subdomains of example.com.

The first server serves file from /var/www/html location while the second subdomain serves files from their respective subdirectories in /var/www/html. For example, the files for test.example.com will be served from /var/www/html/test while the files for data.example.com will be served from /var/www/html/data.


3. Create Test files

Let us create 3 test files – one for example.com, one for test.example.com and one for data.example.com

$ sudo vi /var/www/html/index.html

Add the following line in it

File for example.com and www.example.com

Similarly, create the following files for test.example.com.

$ sudo vi /var/www/html/test/index.html

Add the following line in it.

File for test.example.com

Create the following file for data.example.com

$ sudo vi /var/www/html/data/index.html

Add the following line in it.

File for data.example.com


4. Restart NGINX server

Restart NGINX Server to apply changes.

$ sudo service nginx restart

Open browser and visit http://example.com, http://test.example.com and http://data.example.com. You will see their respective files in the output.

In this article, we have learnt how to setup wildcard subdomains or catch-all subdomains in NGINX.

Also read :

How to Uninstall NodeJS, NPM in Ubuntu
How to “Unable to Find Socket Transport SSL” error in PHP
How to Redirect URL/Page with Anchor Link
How to Convert DocX to PDF in Python
How to Setup SSH Passwordless Login


Leave a Reply

Your email address will not be published. Required fields are marked *