Explain NGINX location block matching order. What is the difference between prefix, exact, and regex matching?
Quick Answer
NGINX processes: exact match (=) first, then longest prefix (^~) stops regex search, then regex (~ or ~*) in order, then longest prefix match. Understanding this prevents routing bugs.
Detailed Answer
Matching Priority (highest to lowest)
1. Exact match =: location = /api/health — matches ONLY /api/health, nothing else. If found, stops immediately. 2. Preferential prefix ^~: location ^~ /static/ — if this is the longest prefix match, SKIP all regex locations. Use for static files to avoid regex overhead. 3. **Regex ~ (case-sensitive) or ~* (case-insensitive): location ~ \.php$ — evaluated in ORDER of appearance in config. First match wins. 4. Standard prefix: location /api/ — longest prefix wins, but only AFTER all regex locations are checked.
Common Pitfall:** A prefix location /api/ can be overridden by a regex location ~ /api/.*\.json — the regex takes priority even though the prefix is more specific. Use ^~ to prevent this.
Best Practice: Use exact matches for health checks, ^~ for static assets, regex only when necessary, and prefix for everything else.
Code Example
# NGINX location matching examples
server {
listen 80;
# 1. Exact match (highest priority)
location = /health {
return 200 'OK';
}
# 2. Preferential prefix (skips regex)
location ^~ /static/ {
root /var/www;
expires 30d;
}
# 3. Regex (evaluated in order)
location ~ \.php$ {
fastcgi_pass php:9000;
}
location ~* \.(jpg|png|gif)$ {
expires 7d;
}
# 4. Standard prefix (lowest priority)
location /api/ {
proxy_pass http://backend;
}
location / {
root /var/www/html;
try_files $uri $uri/ /index.html;
}
}
# Test which location matches:
# /health → exact match =
# /static/app.js → ^~ prefix (skips regex)
# /image.PHP → ~* case-insensitive regex
# /api/users → /api/ prefix
# /about → / prefix (catch-all)Interview Tip
Draw the priority order: = → ^~ → ~ → prefix. The ^~ vs regex precedence is the most commonly misunderstood part and a frequent interview question.