gotchanginxMajorpending
Nginx location matching order
Viewed 0 times
locationmatching orderprefixregexexact matchrouting
Error Messages
Problem
Nginx location blocks don't match in the order they appear, causing unexpected routing behavior.
Solution
Nginx location matching priority (highest to lowest):
Matching algorithm:
Common mistake:
# 1. Exact match (=) - highest priority
location = /api/health {
return 200 'OK';
}
# 2. Preferential prefix (^~) - stops regex search
location ^~ /static/ {
root /var/www;
}
# 3. Regular expression (~, ~*) - first match wins
location ~ \.php$ {
fastcgi_pass php:9000;
}
location ~* \.(jpg|png|gif)$ { # ~* = case insensitive
expires 30d;
}
# 4. Prefix match (longest wins)
location /api/ {
proxy_pass http://backend;
}
location /api/v2/ {
proxy_pass http://backend-v2; # Longer prefix wins
}
location / {
root /var/www/html; # Fallback
}Matching algorithm:
- Check exact matches (
=). If found, stop. - Check prefix matches. Remember the longest match.
- If longest prefix has
^~, stop and use it. - Check regex matches in order. If any matches, use it.
- Otherwise, use the longest prefix match from step 2.
Common mistake:
# Regex BEATS longer prefix (unless ^~)
location /images/ { root /data; } # Prefix match
location ~ /images/.*\.php$ { deny all; } # Regex wins!
# Solution: use ^~ on the prefix
location ^~ /images/ { root /data; } # Now prefix winsWhy
Nginx's location matching is not top-to-bottom like most routing. Understanding the priority prevents requests going to the wrong handler.
Context
Nginx configuration with multiple location blocks
Revisions (0)
No revisions yet.