Sub topic 3
Choosing a server and matching locations
Nginx makes two routing decisions before it forwards a request. It picks a server block, then picks a location block inside it. Most "my proxy sends traffic to the wrong place" problems come from misreading one of these two steps. This chapter covers both so you can predict which block handles any request.
This chapter assumes you can edit Nginx configuration files and know how nested blocks, nginx -t and reload work. It also assumes you can use curl to send HTTP requests.
Step one: selecting a server block
Nginx selects a server block in two stages.
- It filters by the
listendirective. The request's destination IP address and port must match alistenentry. If several server blocks share the same address and port, the next stage chooses among them. - It compares the request's
Hostheader against each candidate'sserver_namevalues.
If no server_name matches, Nginx uses the default server for that address and port. This is the block marked default_server on its listen line. If none is marked, it is the first block in the configuration that listens there.
How server_name values are compared
Nginx tests names in a fixed order and stops at the first category that matches:
- An exact name, such as
example.com. - The longest wildcard that starts with
*, such as*.example.com. - The longest wildcard that ends with
*, such asmail.*. - The first matching regular expression, in file order. Regular expressions start with
~, such as~^api\d+\.example\.com$. - The default server.
Only regular expressions depend on file order. For the other categories, the position of the block does not matter.
Always define a catch-all default
Without an explicit default, a request with an unknown or missing Host header reaches whichever site happens to be first. This often exposes an internal application to scanners that connect by IP address. Define a default that refuses these requests:
server {
listen 80 default_server;
server_name _;
return 444;
}
server {
listen 80;
server_name example.com www.example.com;
location / {
return 200 "example.com site\n";
}
}
server {
listen 80;
server_name api.example.com;
location / {
return 200 "api site\n";
}
}The name _ is only a placeholder that never matches a real host. The default status is carried by default_server, not by the name. Status 444 is an Nginx-specific code that closes the connection without sending a response.
You can test host selection without touching DNS by setting the Host header yourself:
curl -H 'Host: example.com' http://127.0.0.1/
curl -H 'Host: api.example.com' http://127.0.0.1/
curl -H 'Host: unknown.test' http://127.0.0.1/The first two return the site names. The third has its connection closed by the default server, so curl reports an empty reply.
Step two: matching a location
After Nginx selects a server, it matches the request URI against that server's location blocks. The matched URI is normalized first. Percent-encoded characters are decoded, . and .. segments are resolved, and repeated slashes are merged by default. The query string is not part of the match, so /app/?x=1 is matched as /app/.
Location types
| Syntax | Type | Case sensitive | Notes |
|---|---|---|---|
| `location = /path` | Exact | Yes | Matches only that exact URI. Stops searching immediately. |
| `location ^~ /path` | Preferential prefix | Yes | If it is the longest matching prefix, regex locations are skipped. |
| `location /path` | Prefix | Yes | Matches URIs that begin with `/path`. |
| `location ~ regex` | Regex | Yes | Tested in file order. |
| `location ~* regex` | Regex | No | Tested in file order. |
| `location @name` | Named | n/a | Never matched by a URI. Used for internal redirects such as `try_files` and `error_page`. |
The matching algorithm
The order in which locations appear in the file matters only among regular expressions. The steps are:
- If a location with
=matches the URI exactly, use it and stop. - Otherwise, find the longest matching prefix location, whether it uses
^~or no modifier. Remember it. - If that longest prefix has
^~, use it and stop. - Otherwise, test the regex locations in file order. The first one that matches wins.
- If no regex matches, use the remembered longest prefix.
A configuration you can test
Place locations that return text to see which one wins. This avoids needing a backend at all:
server {
listen 80;
server_name example.com;
location / {
return 200 "prefix /\n";
}
location /app/ {
return 200 "prefix /app/\n";
}
location = /app/ {
return 200 "exact /app/\n";
}
location ^~ /static/ {
return 200 "preferential /static/\n";
}
location ~* \.(png|jpg|css)$ {
return 200 "regex image\n";
}
}These are the results for different request URIs:
| Request URI | Winner | Why |
|---|---|---|
| `/index.html` | `prefix /` | Only `/` matches as a prefix. The regex does not match `.html`. |
| `/app/` | `exact /app/` | The exact match ends the search. |
| `/app/users` | `prefix /app/` | Longest prefix, and no regex matches. |
| `/app/logo.png` | `regex image` | `/app/` is a plain prefix, so the regex is tested and matches. |
| `/static/site.css` | `preferential /static/` | The longest prefix uses `^~`, so regexes are skipped. |
| `/photo.PNG` | `regex image` | `~*` ignores case. |
| `/static` | `prefix /` | `/static/` needs the trailing slash to match. |
| `/APP/users` | `prefix /` | Prefix matching is case sensitive. |
Check any row with curl:
curl -H 'Host: example.com' http://127.0.0.1/app/logo.pngThe fourth row is the one that surprises people. A request such as /app/logo.png would not reach the /app/ location, even though that prefix looks like a better fit, because regex locations get a turn whenever the longest prefix lacks ^~.
Applying this to a proxy
In a proxy setup, locations decide which URLs go to the application and which are handled by Nginx. A typical split sends /api/ upstream and serves static files directly:
server {
listen 80;
server_name example.com;
location /api/ {
proxy_pass http://127.0.0.1:3000;
}
location ^~ /assets/ {
root /var/www/example;
}
location ~* \.(png|jpg|css|js)$ {
root /var/www/example;
expires 7d;
}
location / {
proxy_pass http://127.0.0.1:3000;
}
}There is a trap in this layout. A request for /api/chart.png matches the /api/ prefix, but then the image regex also matches, and the regex wins. Nginx would look for the file on disk instead of sending the request to the application. Two ways to fix this:
- Change the API location to
location ^~ /api/so regexes are skipped for it. - Use a narrower regex, anchored to the directories that hold static files.
The first fix is usually simpler and keeps the intent clear.
Common errors
- Wrong site served. The
Hostheader did not match anyserver_name, so the default server answered. Check for typos, a missingwww.variant, or clients that connect by IP address. - Trailing-slash surprises.
location /appmatches/app,/app/and/application, because prefix matching is plain string comparison.location /app/does not match/app. Choose one deliberately, and know that when a prefix location ends in a slash and passes to a proxy, Nginx does not redirect the slash-less URI for you. - Regex order bugs. If two regexes could match the same URI, the earlier one in the file wins. Put the more specific pattern first.
- A location that never runs. A broader
^~prefix or an earlier regex may be capturing the requests. Temporarily add areturn 200marker in each block, as above, to see which one is chosen. - Case assumptions. Prefix locations and
~are case sensitive. Use~*only where you want case-insensitive behavior.
Note that this chapter stops at selection. What Nginx does with the URI once a proxy_pass location is chosen, including how the matched prefix is replaced, is the subject of the next chapter.
Summary of the decision order
- Match the connection's address and port to
listenentries. - Match the
Hostheader toserver_name, or use the default server. - Match the URI to a location: exact first, then the longest prefix (stopping if
^~), then the first matching regex, then the longest prefix.
Exercise
A server block contains location /files/ { ... } and, after it, location ~ \.zip$ { ... }. Which block handles a request for /files/archive.zip, and what one-word change to the first location would make it handle that request instead?
Show answer
The regex location ~ \.zip$ handles it. The prefix /files/ is the longest prefix, but it has no ^~, so Nginx goes on to test the regex locations and the regex matches. Changing the first location to location ^~ /files/ makes Nginx skip the regex step, so the /files/ block handles the request.
Exercise
Two server blocks listen on port 80. One has server_name example.com; and the other has server_name *.example.com;. Neither has default_server. Which block answers a request with Host: example.com, which answers Host: shop.example.com, and which answers Host: other.org?
Show answer
example.com goes to the first block, because exact names are tried first. shop.example.com goes to the second block, which matches the wildcard. other.org matches neither name, so it goes to the default server, which is the first block listed for that address and port, because no block is marked default_server.