set nginx to catch all unhandled virtual hosts

Set NGINX to Catch All Unhandled Virtual Hosts

NGINX allows you to host multiple websites, domains & sub domains on a single server using virtual hosts. When your server gets incoming requests, it checks the host name in the request to see if it matches with any of the virtual hosts, and directs the request to appropriate virtual host accordingly. But sometimes, in spite of creating configurations for different domains, you may get requests containing your IP address or to some other domain linked to your IP address. In such cases, it is advisable to add a catch all virtual host to receive and process all such requests. In this article, we will learn how to set NGINX to catch all unhandled virtual hosts.


Set NGINX to Catch All Unhandled Virtual Hosts

You can set up catch all virtual host using ‘server_name _‘ directive along with using default_server in listen directive, as shown below. Here is an example to have catch all virtual hosts listening to ports 80 (HTTP) and 443 (HTTPS).

server {

   server_name _;

   listen 80 default_server;

   listen 443 ssl default_server;
   ssl_certificate <path to cert>;
   ssl_certificate_key <path to key>;

   root /var/www/default; (or wherever)    

}

In the above server block, we use server_name directive. Instead of setting it to domain name of any of the virtual hosts, we set it to ‘_’.

Next, in the listen directive for ports 80 and 443, we use default_server. These two settings will ensure that any request sent to your server is handled, even if its host name does not match that of any of the virtual hosts configured on your server.

We have added listen directive for both ports 80 and 443 so as to handle both HTTP as well as HTTPS requests. If you want to handle only HTTP requests you can omit listen request to port 443.

Please note, if you listen to port 443, you need to also mention path to SSL certificates using ssl_certificate and ssl_certificate_key directives.

In this article, we have learnt how to catch all unhandled virtual hosts in NGINX.

Also read:

How to Do Case Insensitive Rewrite in NGINX
How to Forward Request to Another Port in NGINX
How to Check if Key Exists in Python Dictionary
How to Get Random Number Between Two Numbers in JavaScript
NGINX Catch All Location

Leave a Reply

Your email address will not be published.