Obey server_name in Nginx

pascal asked:

I want nginx/0.7.6 (on debian, i.e. with config files in /etc/nginx/sites-enabled/) to serve a site on exactly one subdomain (indicated by the Host header) and nothing on all others. But it staunchly ignores my server_name settings?!

In sites-enabled/sub.domain:

server {
  listen 80;
  server_name sub.domain;
  location / { … }
}

Adding a sites-enabled/00-default with

server {
  listen 80;
  return 444;
}

Does nothing (I guess it just matches requests with no Host?)

server {
  listen 80;
  server_name *.domain;
  return 444;
}

Does prevent Host: domain requests from giving results for Host: sub.domain, but still treats Host: arbitrary as Host: sub-domain.

The, to my eyes, obvious solution isn’t accepted:

server {
  listen 80;
  server_name *;
  return 444;
}

Neither is

server {
  listen 80 default_server;
  return 444;
}

Since order seems to be important: renaming 00-default to zz-default, which, if sorted, places it last, doesn’t change anything. But debian’s main config just includes *, so I guess they could be included in some arbitrary file-system defined order?


This returns no content when Host: is not sub.domain as expected, but still returns the content when Host is completely missing. I thought the first block should handle exactly that case!? Is it because it’s the first block?

server {
  listen 80;
  return 444;
}
server {
  listen 80;
  server_name ~^.*$;
  return 444;
}

My answer:


The default virtual host should contain:

server_name _;

This is a catch-all that will match any host name not specified in any other server_name directive.

You are also correct when you note that when server_name is missing, the block matches only requests without a Host: header.

Note that this probably won’t work on nginx 0.7.x, which is antique and horribly out of date, and for which many things have changed. If you insist on using debian, please do yourself a favor and use the dotdeb repositories to keep current with software such as nginx, MySQL, and PHP, for which it’s critical to update much more rapidly than Debian does.


View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.