Common nginx Location Block Patterns

nginx exact, prefix, regex and longest-prefix location match priority rules.

Reference for nginx location block modifiers — exact (=), preferential prefix (^~), case-sensitive (~) and case-insensitive (~*) regex, and plain prefix — with the exact matching priority order nginx applies.

What is nginx's location matching priority order?

First an exact (=) match wins immediately. Otherwise nginx finds the longest matching plain prefix; if that prefix used ^~ it is selected and regexes are skipped. Otherwise regex locations (~ and ~*) are tried in file order and the first match wins. If no regex matches, the longest plain prefix found earlier is used.

What location matching decides

When a request arrives, nginx must choose exactly one location block to handle it. The rules are not simply “first match wins” or “longest wins” — there is a specific priority order that mixes modifiers (=, ^~, ~, ~*, none), prefix length, and file order for regexes. Misunderstanding this order is the source of countless “why is the wrong block serving my request” bugs.

How it works

nginx resolves a location in this order:

  1. Exact location = /path — if it matches, stop. Highest priority.
  2. Find the longest matching plain prefix (location /path and location ^~ /path). Remember it.
  3. If that longest prefix used ^~, select it and skip all regex.
  4. Otherwise evaluate regex locations (~ case-sensitive, ~* case-insensitive) in file order; the first to match wins.
  5. If no regex matches, fall back to the longest plain prefix from step 2.

So exact beats preferential prefix, which beats regex, which beats an ordinary prefix. The tester below runs this exact algorithm against any path and your set of blocks.

Tips and notes

Use = for hot single URIs like / or /favicon.ico to short-circuit matching. Use ^~ /static/ to protect an asset directory from regex handlers. Remember regexes are tried in the order written, so put more specific regex blocks above general ones. A trailing slash changes the prefix, so location /api and location /api/ match different sets of URIs — pick deliberately.