Wildcard records with Nginx to handle custom domains

The solution (at least with my configuration):

In your wildcard record, the 'listen' directive should also include 'default':

listen 80 default;

Don't add a 'server_name' directive because that will cause things to break in ugly, unexpected ways.

Props to Max Cutler for helping me figure this out.


Referring to the official documentation, you have the following possibilities :

server {
  server_name   example.com  *.example.com  www.example.*;
}

server {
  server_name _ *;
}

server {
  server_name example.com *;
}

Note that this has changed in 0.6.x and is now:

server {
  server_name _;
}

Since nginx 0.7.12, an empty server name is supported, to catch the requests without "Host" header:

server {
  server_name "";
}