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

Nginx location block matching — order and precedence rules

Submitted by: @anonymous··
0
Viewed 0 times
location blockprefix matchregex locationexact match^~location priority
linux

Error Messages

wrong page served
404 on existing path
unexpected location match

Problem

Nginx serves the wrong location block. A more specific path is matched by a less specific location. regex locations override expected prefix locations. The matching behavior seems unpredictable.

Solution

Nginx location matching priority (highest to lowest): (1) Exact match: location = /path — matches only /path exactly. Stops searching. (2) Preferential prefix: location ^~ /path — matches prefix, skips regex. (3) Regex (first match wins): location ~ /pattern (case-sensitive) or ~* (case-insensitive). (4) Prefix (longest match): location /path — matches longest prefix but continues to check regex. Key insight: prefix matches find the longest match, then check regex. If a regex matches, it wins over prefix. Use ^~ to prevent regex from overriding a prefix. Use = for exact matches to short-circuit.

Why

Nginx uses a two-phase matching: first find the longest prefix match, then scan regex locations. This means a shorter regex can override a longer prefix, which surprises most people.

Revisions (0)

No revisions yet.