Sub topic 5
Matching host names with server_name
This chapter assumes you can edit files under /etc/nginx with sudo and that you know what the HTTP Host header is. It also assumes Nginx runs from distribution packages under systemd. The chapter covers what server_name accepts, the order Nginx uses when several names could match, and the mistakes that cause the wrong site to answer.
What server_name does
The server_name directive lists the host names a server block answers to. When a request arrives, Nginx compares the request's Host header with the names in each candidate block. listen narrows the candidates by address and port first (see the previous chapter). server_name then picks among the blocks that remain.
A block can list several names, separated by spaces:
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}Both example.com and www.example.com reach this block. The directive is valid only in a server context. Names are compared case-insensitively.
The four kinds of name
Nginx accepts four forms of name. Each has a different priority when several could match.
| Form | Example | Notes |
|---|---|---|
| Exact name | `example.com` | Fastest to match, highest priority |
| Wildcard at the start | `*.example.com` | Matches any subdomain, such as `blog.example.com`. It also matches deeper names such as `a.b.example.com`. |
| Wildcard at the end | `mail.*` | Matches `mail.example.com` and `mail.example.org`. |
| Regular expression | `~^www\d+\.example\.com$` | Starts with `~`. Slowest, and order matters. |
A wildcard may only sit at the very start or the very end of a name, and only as a whole label. www.*.example.com and w*.example.com are invalid. Nginx rejects them during nginx -t.
Wildcard details
The special form .example.com matches both example.com and *.example.com. It is a shortcut for listing the bare name and the wildcard together:
server_name .example.com;This is handy when one block should answer for the bare domain and every subdomain.
Regular expressions
A name starting with ~ is a regular expression. Nginx uses PCRE syntax. Anchor the expression with ^ and $. Without anchors, ~example\.com also matches notexample.com.evil.test.
Escape dots with a backslash, because an unescaped dot matches any character. If the expression contains { or } (for example {2,3}), put the whole name in quotes. Otherwise Nginx reports a parse error.
Named captures become variables you can use later in the block:
server {
listen 80;
server_name ~^(?<subdomain>[a-z0-9-]+)\.example\.net$;
root /var/www/example.net/$subdomain;
}A request for shop.example.net sets $subdomain to shop, so Nginx serves files from /var/www/example.net/shop. This pattern is convenient but risky. The captured text comes from the client, so keep the character class narrow, as above. Never allow . or / in a value that becomes part of a file path.
The matching order
When several server blocks listen on the same address and port, Nginx tests the Host value against the names in this order. The first rule that finds a match wins.
- The exact name.
- The longest wildcard starting with
*, such as*.example.com. - The longest wildcard ending with
*, such asmail.*. - The first regular expression, in the order the blocks appear in the configuration as Nginx reads it.
- The default server for that address and port.
Longer wildcards beat shorter ones because they are more specific. Given *.example.com and *.shop.example.com, a request for a.shop.example.com goes to the second.
Only regular expressions depend on file order. If two blocks both have a matching regex, the one Nginx reads first wins. Files in sites-enabled are included in alphabetical order, so a file named 10-api is read before 20-web.
A worked example with overlapping names
Suppose these three blocks all listen on port 80:
server {
listen 80;
server_name www.example.com;
return 200 "exact\n";
}
server {
listen 80;
server_name *.example.com;
return 200 "wildcard\n";
}
server {
listen 80;
server_name ~^www\d+\.example\.com$;
return 200 "regex\n";
}Test them with curl, using the Host header so DNS is not involved:
curl -H 'Host: www.example.com' http://127.0.0.1/
curl -H 'Host: blog.example.com' http://127.0.0.1/
curl -H 'Host: www2.example.com' http://127.0.0.1/The three requests print exact, wildcard and wildcard. The third result surprises many people. www2.example.com matches both *.example.com and the regex. The wildcard is tested first, so the regex never gets a chance. A regex only wins when no exact name or wildcard matches.
You can also have curl resolve a name for a single request:
curl --resolve example.com:80:127.0.0.1 http://example.com/Names that need care
The empty name and the underscore
If a block has no server_name, its name is the empty string. It matches requests that have no Host header at all. That is rare in practice.
The name _ is not special to Nginx. It is an invalid host name that nobody will request, so it is a convention for catch-all blocks. Combine it with default_server, which a later chapter covers in detail:
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
return 444;
}The name alone does not make a block the default. Without default_server on listen, the default is simply the first block Nginx reads for that address and port.
The port is not part of the name
server_name example.com:8080 is wrong. Nginx strips the port from the Host header before comparing. Use listen 8080; to separate sites by port, and keep server_name to the host name alone.
Duplicate names
If two blocks on the same address and port declare the same exact name, Nginx still starts. It prints a warning during nginx -t:
nginx: [warn] conflicting server name "example.com" on 0.0.0.0:80, ignoredThe second block is ignored for that name. This is a common result of copying a site file and forgetting to edit it. Treat the warning as an error. The nginx -t test passes with a warning, so read its output rather than relying on the exit code alone.
Internationalized names
Write non-ASCII names in their ASCII form (Punycode, which starts with xn--). Browsers send the Punycode form in the Host header, so server_name xn--bcher-kva.example; matches a request for bücher.example.
The canonical name and redirects
Two names for the same site are both valid, and search engines treat them as duplicates. A common approach is to choose one canonical name and redirect the other. Do this with a dedicated block rather than an if inside the main block:
server {
listen 80;
listen [::]:80;
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}The main block then lists only example.com. Exact-name matching sends each request to the right place, and the redirect keeps the path and query string through $request_uri. A later chapter covers redirects in full.
Hash tables and many names
Nginx stores exact and wildcard names in hash tables built at startup. With a handful of sites you never notice. With hundreds of names, or very long ones, Nginx may refuse to start with:
nginx: [emerg] could not build the server_names_hash, you should increase server_names_hash_bucket_size: 64Raise the value in the http block, using a power of two:
http {
server_names_hash_bucket_size 128;
}If it still fails, also raise server_names_hash_max_size. A single very long name, such as a long subdomain, is the usual trigger for the bucket error.
Verifying what Nginx loaded
Dump the full parsed configuration and filter it:
sudo nginx -T | grep -E 'server_name|listen'nginx -T prints every included file, so you see exactly which names are active. Use it when a block seems to be ignored. The usual cause is a missing symlink in sites-enabled or a mistyped name.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Wrong site answers | The name is missing from `server_name`, so the default block handles the request | Add the name, then run `nginx -t` and reload |
| Regex block never used | An exact name or wildcard matches first | Use an exact name, or reorder your design |
| `conflicting server name` warning | Same name declared in two blocks on the same address and port | Remove the duplicate |
| `server_names_hash` error at startup | Many or long names | Raise `server_names_hash_bucket_size` |
| Parse error on a regex | Unquoted `{}` in the pattern | Wrap the name in quotes |
Exercises
Exercise
A server has the blocks server_name *.example.com;, server_name ~^api\d*\.example\.com$; and server_name api.example.com;, all on port 80. Which block answers a request with Host: api.example.com, and which answers Host: api2.example.com?
Show answer
api.example.com goes to the exact-name block, since exact names have the highest priority. api2.example.com goes to the *.example.com wildcard block, because wildcards are tested before regular expressions and the regex is never reached.
Exercise
A colleague writes server_name example.com:8080; to serve a site on port 8080. What is wrong, and what is the correct configuration?
Show answer
Nginx removes the port from the Host header before matching, so the name can never match as written. Use listen 8080; to select the port and server_name example.com; for the name.
Exercise
nginx -t prints conflicting server name "example.org" on 0.0.0.0:80, ignored and still says the test is successful. Why does this matter, and how do you find the two blocks?
Show answer
The test succeeds because Nginx can start, but the second block's name is silently ignored, so that block's content is never served for the name. Run sudo nginx -T | grep -n 'server_name' and look for the repeated name, then remove or rename the duplicate.