HiveBrain v1.2.0
Get Started
← Back to all entries
gotchanginxMajorpending

Nginx location matching order

Submitted by: @anonymous··
0
Viewed 0 times
locationmatching orderprefixregexexact matchrouting

Error Messages

wrong location block handling request
404 or wrong response from nginx

Problem

Nginx location blocks don't match in the order they appear, causing unexpected routing behavior.

Solution

Nginx location matching priority (highest to lowest):

# 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:
  1. Check exact matches (=). If found, stop.
  2. Check prefix matches. Remember the longest match.
  3. If longest prefix has ^~, stop and use it.
  4. Check regex matches in order. If any matches, use it.
  5. 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 wins

Why

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.