Sub topic 7
Location blocks and how requests are matched
This chapter assumes you can edit files under /etc/nginx with sudo and run sudo nginx -t && sudo systemctl reload nginx. It also assumes you know how a server block is chosen by listen and server_name. Here you will learn how Nginx picks one location block inside the chosen server, and how to predict that choice without trial and error.
What a location block does
A location block holds directives that apply to requests whose URI matches a pattern. Nginx first selects a server block. It then compares the request URI against that server's locations and runs the directives of exactly one of them. If no location matches, the server block's own directives apply.
Two details affect every match:
- Nginx matches against the normalized URI. It decodes
%XXescapes, resolves.and..segments, and collapses repeated slashes. A request for/docs//a/../bis matched as/docs/b. - Matching uses only the path. The query string (
?x=1) is ignored, so/page?id=3matches the same location as/page.
Location syntax and modifiers
The general form is location [modifier] pattern { ... }. The modifier decides how the pattern is read.
| Syntax | Meaning | Kind | Column |
|---|---|---|---|
| `location /docs/` | URI starts with `/docs/` | Prefix | |
| `location = /login` | URI is exactly `/login` | Exact | |
| `location ^~ /static/` | Prefix match that, if it is the longest one, skips regex checks | Prefix | |
| `location ~ \.php$` | Case-sensitive regular expression | Regex | |
| `location ~* \.(jpg\ | png)$` | Case-insensitive regular expression | Regex |
| `location @fallback` | Named location, reachable only by internal redirects | Named |
Nginx uses PCRE regular expressions. If a regex contains { or } or spaces, wrap it in quotes. For example, location ~ "^/id/[0-9]{4}$".
The matching algorithm
Order in the file matters for regex locations and does not matter for prefix locations. Nginx follows these steps:
- Test every prefix location, including
=and^~ones, and remember the longest one that matches. - If an exact (
=) location matches the whole URI, use it and stop. - If the longest prefix match carries the
^~modifier, use it and stop. - Otherwise, test the regex locations in the order they appear in the configuration. Use the first one that matches and stop.
- If no regex matches, use the longest prefix match remembered in step 1.
The key consequence is that a regex location beats a plain prefix location, even a much longer prefix, whenever the regex matches. People often find this surprising.
A worked example
This server block returns a label that names the location that handled each request. That makes the matching visible. Save it as /etc/nginx/conf.d/locations-demo.conf.
server {
listen 8080;
server_name localhost;
default_type text/plain;
location = / {
return 200 "A: exact /\n";
}
location / {
return 200 "B: prefix /\n";
}
location /docs/ {
return 200 "C: prefix /docs/\n";
}
location ^~ /static/ {
return 200 "D: ^~ /static/\n";
}
location ~* \.(jpg|png)$ {
return 200 "E: regex images\n";
}
location ~ ^/docs/.*\.pdf$ {
return 200 "F: regex docs pdf\n";
}
}Test the file, reload, and send several requests:
sudo nginx -t && sudo systemctl reload nginx
for path in / /index.html /docs/intro /docs/guide.pdf \
/static/logo.png /photos/cat.PNG /docs/diagram.jpg \
"/docs/guide.pdf?v=2"; do
printf '%-24s -> ' "$path"
curl -s "http://localhost:8080$path"
doneThe expected results, with the reasoning for each:
| Request | Handled by | Why |
|---|---|---|
| `/` | A | The exact match wins immediately. |
| `/index.html` | B | Only `/` matches as a prefix, and no regex matches. |
| `/docs/intro` | C | `/docs/` is the longest prefix, and no regex matches. |
| `/docs/guide.pdf` | F | `/docs/` is the longest prefix, but it lacks `^~`. The regex F matches, so it wins. |
| `/static/logo.png` | D | The longest prefix has `^~`, so regexes are never tested. |
| `/photos/cat.PNG` | B or E | Prefix `/` is remembered. Regex E matches, case-insensitively, so E is used. |
| `/docs/diagram.jpg` | E | Regex E appears before F in the file and matches first. |
| `/docs/guide.pdf?v=2` | F | The query string is ignored. |
The /photos/cat.PNG row resolves to E. The "B or E" wording shows the two candidates Nginx weighs, and the regex wins.
Ordering rules you must remember
- Prefix locations are order independent.
/docs/and/docs/api/give the same result in either order, because the longest match wins. - Regex locations are order dependent. If two regexes can match the same URI, the one written first handles it. Put the more specific regex above the general one.
- Duplicate patterns are rejected. Two locations with the identical modifier and pattern in one server make
nginx -tfail with a "duplicate location" error.
Common patterns
A catch-all location / is a good default. It handles anything the other locations do not claim, and it is where you usually put try_files for a static site or proxy_pass for an application.
To keep a static directory away from regex rules, use ^~:
location ^~ /assets/ {
root /var/www/example.com;
expires 30d;
}Without ^~, a regex such as \.php$ could capture /assets/upload.php and send it to your application. Nginx would then run a file you meant to serve as static content.
To send regex-matched requests to different handlers, order them from specific to general:
location ~ ^/api/v2/ {
proxy_pass http://127.0.0.1:3001;
}
location ~ ^/api/ {
proxy_pass http://127.0.0.1:3000;
}If these were in the opposite order, the /api/ regex would match /api/v2/ URIs first, and the v2 backend would never be used. Prefix locations with proxy_pass avoid this problem entirely, so prefer them when you do not need a regex.
Named locations and internal redirects
A named location starts with @ and cannot be requested directly. Other directives send requests to it. A common case is a static-first setup with an application fallback:
location / {
try_files $uri $uri/ @app;
}
location @app {
proxy_pass http://127.0.0.1:3000;
}try_files checks for a real file, then a directory, and finally hands the request to @app. When a directive such as try_files, index, or error_page rewrites the URI internally, Nginx runs the matching process again on the new URI. That restart can land in a different location than the original request did.
Common errors
- A regex steals requests from a prefix. A location for
/images/seems ignored because~* \.(jpg|png)$also matches the files inside it. Add^~to the prefix or restrict the regex. - Unanchored regexes.
~ /adminmatches/blog/admin-tips. Anchor with^and$where you mean the start or end of the path. - Forgetting the dot escape.
~ .php$matches/aphp. Write\.php$. - Trailing slash in
proxy_pass. Withlocation /api/ { proxy_pass http://127.0.0.1:3000/; }, the matched/api/part is replaced by/, so/api/usersreaches the backend as/users. With no URI inproxy_pass, the original path is passed unchanged. This rule applies to prefix locations only. It does not apply inside regex locations. - Using
ifinstead oflocation.ifinside a location behaves in surprising ways. Use separate locations whenever you can.
Debugging which location matched
When a request does not behave as expected, add a temporary response header in each location. Alternatively, log the variable $uri and the status in a custom log_format. The labeled return statements used in this chapter are the quickest method. Also remember that nginx -T prints the full effective configuration, including included files. This lets you see every location in the order Nginx sees it.
Exercise
Given the locations below, which one handles a request for /files/Report.PDF? Then say what changes if ^~ is added to location /files/.
location /files/ { ... } # 1
location ~ \.pdf$ { ... } # 2
location ~* \.pdf$ { ... } # 3
Show answer
Location 3 handles it. The longest prefix is /files/ (location 1), but it has no ^~, so Nginx tests regexes in file order. Location 2 is case-sensitive and does not match .PDF. Location 3 is case-insensitive and matches, so it wins. If ^~ is added to location 1, the longest prefix carries ^~, so Nginx stops before any regex and location 1 handles the request.
Exercise
A site has location / and location = /health. A request arrives for /health/. Which location handles it, and why?
Show answer
location / handles it. The exact match = /health requires the whole URI to equal /health. The URI /health/ has a trailing slash, so the exact location does not match, and the only matching prefix is /.