Parsing the “server_name” Directive to Choose a Match

Next, to further evaluate requests that have equally specific listen directives, Nginx checks the request’s “Host” header. This value holds the domain or IP address that the client was actually trying to reach.

Nginx attempts to find the best match for the value it finds by looking at the server_name directive within each of the server blocks that are still selection candidates. Nginx evaluates these by using the following formula:

  • Nginx will first try to find a server block with a server_name that matches the value in the “Host” header of the request exactly. If this is found, the associated block will be used to serve the request. If multiple exact matches are found, the first one is used.
  • If no exact match is found, Nginx will then try to find a server block with a server_name that matches using a leading wildcard (indicated by a * at the beginning of the name in the config). If one is found, that block will be used to serve the request. If multiple matches are found, the longest match will be used to serve the request.
  • If no match is found using a trailing wildcard, Nginx then evaluates server blocks that define the server_name using regular expressions (indicated by a ~ before the name). The first server_name with a regular expression that matches the “Host” header will be used to serve the request.
  • If no regular expression match is found, Nginx then selects the default server block for that IP address and port.

Each IP address/port combo has a default server block that will be used when a course of action can not be determined with the above methods. For an IP address/port combo, this will either be the first block in the configuration or the block that contains the default_server option as part of the listen directive (which would override the first-found algorithm). There can be only one default_server declaration per each IP address/port combination.