Default servers in nginx


Apache served me well from my teens till lighttpd, then in the last year I’ve moved all my own stuff to nginx. If you come from the perspective of someone learning to configure a webserver from scratch (without preconceived notions of how they should be configured from Apache), its rather lovely to configure and use.

The cloud instance that runs this site also serves several others, so I have a series of virtual hosts, to borrow a term from Apache. Each domain has its own configuration within sites-available, then the servers I want active are symlinked into sites-enabled.

For example:

ls -l /etc/nginx/sites-enabled
=> rubenerd -> /etc/nginx/sites-available/rubenerd
=> tigerintherain -> /etc/nginx/sites-available/tigerintherain

If this server receives an http request without a header, or I’ve pointed a domain with my DNS server to it that doesn’t have a corresponding config, nginx will return the first defined server block. In this case, rubenerd. But what if we want to return tigerintherain?

The first approach would be familar to those configuring GRUB: simply prepend 00 to the first virtual host file. I’ve tested this, and it works. It’s also a terrible hack, and it made me feel bad.

The alternative is to append “default_server” to the listening port of the server you want nginx to default to. For example:

server {
    listen 80 default_server;

I prefer this approach because it’s self documenting. The nginx docs point out you can use an invalid character and it’ll still work:

server {
    listen 80 default_server;
    server_name _;  ## resolves

Now you can reboot nginx, and be on your way.

Author bio and support


Ruben Schade is a technical writer and IaaS engineer in Sydney, Australia who refers to himself in the third person in bios. Wait, not BIOS… my brain should be EFI by now.

The site is powered by Hugo, FreeBSD, and OpenZFS on OrionVM, everyone’s favourite cloud infrastructure provider.

If you found this post helpful or entertaining, you can shout me a coffee or buy some silly merch. Thanks!