Tuesday, August 27, 2024

Nginx uses 1st available server configuration when domain name not resolved

If you host several sites on nginx (which means that you also have several domain names pointing to your server's IP address) then you may face with the following issue. Suppose that we have 3 domain names pointing to our server's IP with running nginx:

example1.com
example2.com
example3.com

Sites example1.com and example2.com are configured in nginx, but there is no example3.com. The problem is that by default nginx will still proxy example3.com to 1st available server config (depending in which order they are defined in nginx.conf file, let's say example1.com in our example) which may be quite confusing because we requested example3.com but see content of example1.com in browser window (in browser address bar we will still see example3.com).

In order to avoid this behavior we need to add default server configuration to nginx.conf which will return 404 like that:

server {
	listen 80 default_server;
	server_name  _;
	return 404;
}

Now if we will try to open example3.com we will see 404 page returned by nginx:

which is more clear and expected behavior from my point of view.