Sub topic 7
How Nginx picks the server block for a request
This chapter assumes you can read Nginx configuration, have at least two server blocks defined, and know that an HTTP/1.1 request carries a Host header. It covers the selection algorithm itself. Later chapters cover testing, default servers and redirects in more detail.
The two-stage decision
When a request arrives, Nginx does not look at every server block at once. It decides in two stages:
- It narrows the candidates by the address and port the connection arrived on, using the
listendirectives. - Among the blocks that listen there, it picks one by comparing the request's
Hostheader with eachserver_name.
If stage 2 finds no match, Nginx falls back to the default server for that address and port. The location blocks inside the chosen server are evaluated only after the server block is picked.
Stage 1: matching listen
Each listen directive names an address, a port, or both. A request is matched against these in a specific way:
- Nginx first looks for the most specific address. A block with
listen 192.0.2.10:80;wins over a block withlisten 80;for connections arriving on 192.0.2.10. - A bare
listen 80;is the same aslisten 0.0.0.0:80;. It matches any IPv4 address on that port that has no more specific listener. listen [::]:80;is the IPv6 equivalent.- If a block has no
listendirective, Nginx uses*:80when running as root, or*:8000otherwise.
Only after the listener is chosen does Nginx look at names. Blocks that listen on other addresses or ports are ignored, even if their server_name matches exactly.
The practical consequence is that the same name in two blocks is only a conflict when both blocks share a listener. This is how a name can serve HTTP on port 80 in one block and HTTPS on port 443 in another.
Stage 2: matching server_name
For the candidates that share the chosen listener, Nginx compares the Host header (with any port removed) against every server_name value. It tests the following forms in a fixed order and stops at the first form that matches:
| Order | Form | Example |
|---|---|---|
| 1 | Exact name | `example.com` |
| 2 | Longest wildcard starting with `*` | `*.example.com` |
| 3 | Longest wildcard ending with `*` | `mail.*` |
| 4 | First matching regular expression, in file order | `~^www\d+\.example\.com$` |
Two details matter here.
- Exact names win over everything. A block with
server_name www.example.com;beats a block withserver_name *.example.com;for the hostwww.example.com, regardless of which appears first in the file. - Regular expressions are the only form where order in the configuration matters. Nginx uses the first regex that matches, reading in the order the blocks are loaded. A regex name starts with
~.
Wildcards can only have * at the start or the end of a name, not in the middle. www.*.example.com is invalid. The special form .example.com matches both example.com and every subdomain, and is a shorter way to write example.com *.example.com.
Capturing from a regular expression
A regular expression server_name can capture part of the host and reuse it as a variable. This lets one block serve many subdomains from matching directories:
server {
listen 80;
server_name ~^(?<subdomain>[a-z0-9-]+)\.example\.net$;
root /var/www/$subdomain/html;
}A request for shop.example.net uses /var/www/shop/html. Use this with care. The captured value comes straight from the client, so restrict the pattern to characters you accept, as the character class above does. Also remember that every request now causes a regex evaluation, and a missing directory only shows up as a 404 at request time, not when you run nginx -t.
What counts as the Host
Nginx takes the name from the Host header. It ignores the port part, so Host: example.com:8080 is compared as example.com. A few special cases follow from this:
- With HTTP/1.0 clients that send no
Hostheader, no name can match. The request goes to the default server for the listener. - A request using an absolute URI, such as
GET http://example.org/ HTTP/1.1, uses the host from the request line in preference to theHostheader. - For TLS connections, the certificate is chosen earlier, using the SNI name from the handshake, but the server block for the request is still chosen from the
Hostheader. A client can send an SNI name for one site and aHostfor another. The chapter on HTTPS covers the consequences.
The default server
The default server for a listener is the block that answers when stage 2 finds no match. By default, it is the first block defined for that address and port in the loaded configuration. You can name it explicitly with the default_server parameter on listen:
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
return 444;
}Two points to watch:
- The default is per listener (address and port pair), not global. A block that is default for
*:80is not automatically default for*:443. - Declaring
default_servertwice for the same listener is a configuration error, andnginx -treports it.
The name _ has no special meaning to Nginx. It is only a name that is unlikely to appear in a real Host header. Leaving it out does not change which block is the default.
Why file order can change which site answers
Because the implicit default is "first loaded", the order of include lines becomes part of your configuration. With the Debian layout, /etc/nginx/sites-enabled/* is read in alphabetical order. If you never mark a default, adding a site named 000-site can quietly change which site answers unknown hosts. Mark the default explicitly and the problem disappears.
A worked example
Consider these blocks, all listening on *:80:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
}
server {
listen 80;
server_name *.example.com;
root /var/www/wildcard/html;
}
server {
listen 80;
server_name ~^api\d+\.example\.com$;
root /var/www/api/html;
}
server {
listen 80 default_server;
server_name _;
return 444;
}The table shows what each Host value selects:
| Host header | Block chosen | Reason |
|---|---|---|
| `example.com` | First | Exact match |
| `www.example.com` | First | Exact match beats the wildcard |
| `blog.example.com` | Second | Wildcard match |
| `api2.example.com` | Second | The wildcard is checked before regular expressions, so the regex block is never reached |
| `example.org` | Fourth | No match, so the default server answers |
| (no Host header) | Fourth | No name to match, so the default server answers |
The api2.example.com row is the usual surprise. The wildcard *.example.com matches first, so the regex block is dead configuration. To make the regex win, replace the wildcard with a more specific exact name, or drop the wildcard block and let the regex handle the subdomains it needs.
Checking your reasoning
Do not guess which block answers. Send a chosen Host header at the local address and read the result:
curl -s -o /dev/null -w '%{http_code}\n' -H 'Host: api2.example.com' http://127.0.0.1/To see which block was used, give each block a different root or a distinct add_header value, or write each to its own access log. Nginx also supports a debug log, but the per-site log approach is usually enough.
Common errors
- A conflicting server name warning. Nginx prints
conflicting server name "example.com" on 0.0.0.0:80, ignoredwhen two blocks on the same listener claim the same exact name. The second one is ignored. Search withgrep -R "server_name" /etc/nginx/to find the duplicate. - The wrong site answers. Typically the
Hostdid not match any name, so the default server (often the first alphabetically) answered. Check for a typo inserver_name, a missingwwwvariant, or a request made by IP address. - A block seems ignored. Check that its
listendiffers from the one you expect. A block withlisten 8080;never sees traffic on port 80. - A regex never fires. A wildcard or exact name earlier in the matching order took the request, as in the worked example.
Summary of the rules
- Filter by listener: most specific address and port first.
- Match
Hostagainst names: exact, then leading wildcard, then trailing wildcard, then first matching regex. - If nothing matches, use the listener's default server, which is the first block unless
default_serversays otherwise. - Evaluate
locationblocks only inside the chosen server.
Exercise
A server has three blocks on listen 80;. Block A has server_name *.example.com;. Block B has server_name ~^img\d+\.example\.com$;. Block C has server_name img1.example.com; and appears last in the file. Which block answers a request with Host: img1.example.com, and which answers Host: img2.example.com?
Show answer
Block C answers img1.example.com, because an exact name beats wildcards and regular expressions no matter where the block appears in the file. Block A answers img2.example.com, because the leading wildcard is checked before regular expressions, so Block B's pattern is never reached.
Exercise
You add a new site file named 000-new to sites-enabled. None of your server blocks use default_server. Visitors who reach the server by IP address now see the new site. Why, and what is the fix?
Show answer
The implicit default server for a listener is the first block loaded, and sites-enabled is read alphabetically, so 000-new is now first. Fix it by adding default_server to the listen directives of a catch-all block (for example one returning 444), so the default no longer depends on file order.