TExcelTAD

Location Matching Order

Once a server block is chosen, Nginx picks one location for the request URI. The rules are not "first match in the file" and not "most specific wins"; they are a short algorithm with two kinds of location, and nearly every "why is this location ignored?" question is answered by it.

The two kinds

Syntax Kind Matches
location = /path exact only exactly /path
location /path prefix URIs starting with /path
location ^~ /path prefix, "stop regex search" like prefix, but if it is the longest prefix, regexes are skipped
location ~ regex regex, case-sensitive PCRE match anywhere in the URI
location ~* regex regex, case-insensitive
location @name named never matched by URI; only a target of try_files, error_page

The algorithm

  1. If an exact (=) location matches, use it and stop.
  2. Find the longest matching prefix location (file order doesn't matter here). Remember it.
  3. If that longest prefix has ^~, use it and stop.
  4. Check regex locations in file order; the first one that matches wins.
  5. If no regex matched, use the remembered longest prefix.

So a regex beats a longer prefix, unless that prefix is marked ^~. The URI being matched is the normalised path: percent-decoded, with /./ and /../ resolved and double slashes merged, and without the query string.

bash · try it yourself
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log stderr;
events {}
http {
  access_log off;
  default_type text/plain;
  server {
    listen 127.0.0.1:8080;
    location = /            { return 200 "1 exact =/\n"; }
    location /              { return 200 "2 prefix /\n"; }
    location /static/       { return 200 "3 prefix /static/\n"; }
    location ^~ /assets/    { return 200 "4 prefix ^~ /assets/\n"; }
    location ~* \.(png|jpg)$ { return 200 "5 regex images\n"; }
    location ~ ^/static/admin { return 200 "6 regex /static/admin\n"; }
  }
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
for u in / /index.html /static/app.css /static/logo.PNG /assets/logo.png /static/admin/x.png /static/../assets/a.png "/a.png?x=1"; do
  printf '%-22s -> ' "$u"; curl -s --path-as-is "127.0.0.1:8080$u"
done
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null
/                      -> 1 exact =/
/index.html            -> 2 prefix /
/static/app.css        -> 3 prefix /static/
/static/logo.PNG       -> 5 regex images
/assets/logo.png       -> 4 prefix ^~ /assets/
/static/admin/x.png    -> 5 regex images
/static/../assets/a.png -> 4 prefix ^~ /assets/
/a.png?x=1             -> 5 regex images

Walk through a few:

  • /static/logo.PNG: the longest prefix is /static/ (3), but regexes are checked next and ~* (case-insensitive) matches .PNG, so 5 wins.
  • /assets/logo.png: the longest prefix is ^~ /assets/, so regexes are never consulted and the image regex doesn't get it.
  • /static/admin/x.png: both regexes match; the first one in the file (5, images) wins, not the "more specific" one. Put specific regexes before general ones.
  • /static/../assets/a.png: normalised to /assets/a.png before matching (--path-as-is stops curl from cleaning the path itself).
  • /a.png?x=1: the query string is not part of the match.

Nested locations and a common mistake

Locations can be nested, which keeps regexes scoped to one part of the site:

nginx
location /static/ {
    root /srv/shop;
    location ~* \.(css|js)$ { expires 30d; }     # only considered for /static/... URIs
}

A classic bug is a regex location for PHP or for "all images" that unintentionally captures URIs under a prefix you thought was protected:

nginx
location /private/ { deny all; }
location ~ \.pdf$ { root /srv/files; }          # /private/report.pdf: the regex wins, deny is skipped!

/private/report.pdf matches the prefix, but the regex is checked next and wins, so the file is served. Fix it with location ^~ /private/ { deny all; }. Here it is, broken and fixed:

bash · try it yourself
mkdir -p files/private && echo "secret numbers" > files/private/report.pdf
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log error.log;
events {}
http {
  access_log off;
  server {
    listen 127.0.0.1:8080;
    location /private/ { deny all; }
    location ~ \.pdf$  { root files; }
  }
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
echo "before: [$(curl -s -o /dev/null -w '%{http_code}' 127.0.0.1:8080/private/report.pdf)] $(curl -s 127.0.0.1:8080/private/report.pdf)"
sed -i 's|location /private/|location ^~ /private/|' nginx.conf
nginx -p "$PWD" -c nginx.conf -e stderr -s reload 2>/dev/null; sleep 0.5
echo "after:  $(curl -s -o /dev/null -w '[%{http_code}]' 127.0.0.1:8080/private/report.pdf)"
grep -o "access forbidden by rule.*request: \"[^\"]*\"" error.log
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null
before: [200] secret numbers
after:  [403]
access forbidden by rule, client: 127.0.0.1, server: , request: "GET /private/report.pdf HTTP/1.1"

Denials are written to the error log (at level error), not only the access log: grepping it for access forbidden is a quick audit of which rules fire.

Exact matches for hot paths

location = / and location = /healthz are matched first and end the search immediately, so they are also the cheapest. For a site where / is a heavy page and everything else goes to a different backend, location = / is the clean way to separate them.

Tip: to see which location handled a request on a live server, temporarily add add_header X-Location "static-regex" always; to the candidates, or log $uri together with a variable set in each location.

Test yourself

Locations: location /images/ {…} and location ~ \.jpg$ {…}. Which handles /images/cat.jpg?

  1. /images/, the longer prefix
  2. The regex: after the longest prefix is found, regexes are checked and the first match wins
  3. Whichever is first in the file
  4. Both

Two regex locations both match a URI. Which one is used?

  1. The longer regex
  2. The first one in the configuration file
  3. The last one
  4. The case-insensitive one

Which location type ends the search immediately when it matches?

  1. location /
  2. location = /path (exact)
  3. location ~* …
  4. location @name