Web & Networking

Nginx Location Matching in the Order That Matters

Understand exact, prefix, and regular-expression locations before adding another Nginx block.

2 min read
#nginx#web server#configuration#routing

A broad waterfall falling through mist beneath a dark ridge

Photo: Unsplash.

Nginx location blocks are not evaluated simply from top to bottom. The matching process becomes easier to predict when exact, prefix, and regular-expression locations are considered separately.

Consider this server:

server {
    listen 80;

    location = /health {
        return 200 "ok\n";
    }

    location /assets/ {
        root /srv/site;
    }

    location ^~ /downloads/ {
        root /srv/files;
    }

    location ~* \\.(jpg|png|webp)$ {
        expires 7d;
    }

    location / {
        proxy_pass http://app;
    }
}

For a request, Nginx first checks prefix locations and remembers the longest match. An exact = match ends the search immediately. If the longest prefix uses ^~, regular expressions are skipped. Otherwise, regular-expression locations are tested in configuration order, and the first matching regex wins. If none matches, Nginx uses the remembered longest prefix.

That means:

  • /health uses the exact block.
  • /assets/app.css uses /assets/ because the image regex does not match.
  • /assets/logo.png can be captured by the regex location, despite /assets/ being the longest prefix.
  • /downloads/photo.png stays in the ^~ /downloads/ block and skips regex testing.
  • everything else reaches location /.

If images under /assets/ must always use the asset configuration, make that prefix ^~ or restructure the configuration deliberately.

Test before reload

Always validate syntax first:

sudo nginx -t

Then reload rather than stopping the server:

sudo systemctl reload nginx

Test representative paths with headers visible:

curl -I http://127.0.0.1/health
curl -I http://127.0.0.1/assets/logo.png
curl -I http://127.0.0.1/downloads/photo.png

When the result is surprising, reduce the configuration to the competing locations and write down which rule should win. Adding another regex without understanding the current match order usually makes the next surprise harder to explain.

Reference