Blog

How to configure Nginx to return an error for requests without a matching host

When you host multiple apps on the same server using Nginx, you probably define multiple virtual servers like this:

server {
  server_name my-awesome-app.com;
  ...
}

server {
  server_name another-brilliant-app.com;
  ...
}

server {
  server_name such-a-fantastic-app.com;
  ...
}

Then you set up a monitoring servive like Pingdom for each app to make sure you are notified if anything bad should happen and one of the apps would go down. The next day a coworker decides such-a-fantastic-app.com is no longer needed and removes that server blog from the Nginx config. But hey, since you set up monitoring, you will get a notification immediately, right?

Well, you guessed it, WRONG!

Once the last server block is removed, if you go to such-a-fantastic-app.com in your browser, you will be forwarded to my-awesome-app.com. From the Nginx docs:

If the "Host" header field does not match a server name, NGINX will route the request to the default server for this port. The default server is the first one listed in the nginx.conf file. [...]

I'm not sure why this is the default since I can't imagine a situation where this behavior would be useful, but maybe there is some reason for this. What I want to happen, though, is for Nginx to return an error for all requests whose host does not match any of the defined server_names. This can be achieved quite easily by adding this server block to the Nginx config file:

server {
  listen 80 default_server;
  return 444;
}

What it does is to explicity define a default server, so it's not the first defined server anymore, and return Nginx' non-standard code 444 which simply closes the connection.

Discuss this post on Hacker News

Ideas? Constructive criticism? Think I'm stupid? Let me know in the comments!