11

I have multiple "server" blocks in my nginx.conf. The documentation seems wrong about the order in which server_name matching takes places.

My conf looks something like:

server { listen 80 server_name domain.com *.domain.com # do stuff } server { listen 80 server_name sub.domain.com *.sub.domain.com # do something else } 

I'm trying to figure out why requests with host = www.sub.domain.com are going to the correct place (the second server), when the documentation indicates it should be going to the first server.

Nginx documentation indicates that the server blocks are checked "in order" for matches, meaning any request with the host *.sub.domain.com should be caught by the first server, not the second server. (http://wiki.nginx.org/HttpCoreModule#server_name)

Also, the * wildcard matches any number of subdomain parts, so *.domain.com matches www.sub.domain.com. (http://nginx.org/en/docs/http/server_names.html#wildcard_names)

If this documentation is wrong, what is the actual matching order?

2 Answers 2

21

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)
2
  • Dude! regular expression should be before asterisks because regex is more specific, am I wrong? Commented Oct 26, 2020 at 17:17
  • 2
    @ObayAbd-Algader yes you’re wrong. Regexps are the slowest matching method, so they’re only tested at the end. You should use exact names or wildcards when possible. Commented Sep 22, 2022 at 14:14
3

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.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.