nginx: "server_name" resolution order?

Solution 1:

From the nginx documentation (http://nginx.org/en/docs/http/server_names.html):

When searching for a virtual server by name, if name matches more than one of the specified variants, e.g. both wildcard name and regular expression match, the first matching variant will be chosen, in the following order of precedence:

  1. exact name
  2. longest wildcard name starting with an asterisk, e.g. “*.example.org”
  3. longest wildcard name ending with an asterisk, e.g. “mail.*”
  4. first matching regular expression (in order of appearance in a configuration file)

Solution 2:

The documentation says:

Compares the Host header of the incoming HTTP request against the server { ... } blocks in the Nginx configuration files and selects the first one that matches.

What is seeming to happen is that it chooses the best match from all the server blocks, so www.sub.domain.com, matching the second config. I have no documentation to back that up, so you may run some tests to confirm that behavior. There is also this doc talking about name resolution.