Order nginx uses to match a location
- Exact match
=— stops immediately. - Longest prefix match across plain prefixes and
^~; if the winner has^~, the search stops. - Regular expressions
~and~*strictly top to bottom in file order — the first match wins. - If no regex matches, nginx falls back to the longest prefix from step 2 (Config anatomy).
Before and after
# Trap: /static/logo.png hits the ~* \.png$ regex instead of /static/
location /static/ {
alias /srv/static/;
}
location ~* \.png$ {
expires 7d;
}
# Right: ^~ skips regex checks for everything under /static/
location ^~ /static/ {
alias /srv/static/;
expires 30d;
}
location ~* \.png$ {
expires 7d;
}
If it doesn’t work
Directives in location /static/ (such as expires or alias) don’t apply to .png and .js files
- Cause
- The same
serverblock haslocation ~* \.(png|jpg|js)$further down, and the regex overrode the plain prefix. - Fix
- Add the
^~modifier (location ^~ /static/) to stop the search before regex matching.
A deny rule in location ~* /uploads/.*\.php$ never triggers
- Cause
- It sits below
location ~ \.php$: among regex locations, the first match in file order wins. - Fix
- Move the more specific regex above the general
location ~ \.php$block (PHP-FPM).