Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 30 ยท Nginx Configuration

Location Blocks and Matching Order

Master Nginx location blocks: exact, prefix, ^~ and regex modifiers, the longest-prefix rule, evaluation order, named and nested locations, root vs alias and try_files.

Once Nginx has picked a server, it has to decide how to handle the URL path. That is the job of location blocks, and they are where most Nginx configurations get subtle. Several locations can match the same URL, and the one that wins is not "the first one in the file" and not always "the most specific". It depends on a two-phase algorithm with a handful of modifiers. Learn that algorithm once and a whole class of puzzles ("why is my regex ignored?", "why does the wrong block serve my images?") disappears.

Real Nginx cannot run in this page, so real configuration is read-only. The runnable stand-ins are a JavaScript implementation of the matching algorithm that you can feed any URL, and a path calculator that shows what root, alias and try_files really do.

Location syntax

A location has an optional modifier, a pattern and a block:

NGINX
location = /            { ... }   # exact match
location /images/       { ... }   # prefix match
location ^~ /static/    { ... }   # prefix match that stops regex checking
location ~ \.php$       { ... }   # regex, case-sensitive
location ~* \.(jpg|png)$ { ... }  # regex, case-insensitive
location @fallback      { ... }   # named location (internal use only)

What gets matched is the normalized URI path: percent-escapes decoded, repeated slashes collapsed, . and .. segments resolved, and without the query string. So /images/logo.png?v=2 is tested as /images/logo.png.

Modifier Type Meaning
(none) prefix the URI starts with the pattern
= exact the URI equals the pattern exactly
^~ prefix like a prefix, but if it is the longest match, skip regex checks
~ regex case-sensitive regular expression
~* regex case-insensitive regular expression

The matching algorithm

Nginx applies the same procedure to every request:

  1. If an = location matches exactly, use it and stop.
  2. Among all prefix locations (plain and ^~), find the one with the longest matching prefix. Remember it.
  3. If that longest prefix has the ^~ modifier, use it and stop.
  4. Otherwise test the regex locations in the order they appear in the configuration. The first one that matches wins.
  5. If no regex matched, use the longest prefix remembered in step 2.

Two things follow that people forget. Prefix locations are compared by length, so their order in the file does not matter. Regex locations are compared by order, so the first one in the file that matches wins even if a later regex is more precise. And a regex beats a plain prefix, however long that prefix is, unless the prefix carries ^~.

flowchart TD
    A["Normalized URI"] --> B{"Exact (=) match?"}
    B -- yes --> Z["Use it"]
    B -- no --> C["Find the longest prefix match"]
    C --> D{"Is it marked ^~ ?"}
    D -- yes --> Z
    D -- no --> E{"First matching regex<br/>in file order?"}
    E -- yes --> Z
    E -- no --> F["Use the remembered prefix"]

Exact wins first, then a ^~ prefix, then the first regex, then the longest prefix.

Pick the right modifier

= One exact URL, checked first.
none Longest prefix, but regexes may override.
^~ Longest prefix that blocks regex checks.
~ and ~* First match in file order wins.

Use ^~ for directories you never want a regex to steal.

1 / 2

Simulation: a location matcher

The script below implements the five steps. Each location has a modifier, a pattern and a label. For every test URL it prints which location wins and the step that decided it. Run it, and predict the result of each URL before you read the output.

JS Which location handles this URL?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look closely at three results. /images/logo.png is a prefix match for /images/, yet the image regex wins, because step 4 comes before falling back to the prefix. /static/logo.png ends in .png too, but ^~ /static/ is the longest prefix and stops the search, so no regex is tried. And /images/../static/app.js?v=2 is normalized to /static/app.js before matching, so the /images/ prefix never enters the picture.

Notice also that the plain / prefix matches everything, so it is the fallback for any URL nothing else claims. That is why nearly every configuration has a location / block.

Named locations and nested locations

A named location starts with @ and can never be matched by a URL. It exists to be a target for try_files or error_page, which jump to it internally:

NGINX
location / {
    try_files $uri $uri/ @app;
}
location @app {
    proxy_pass http://127.0.0.1:3000;
}

Locations can also be nested. A regex location inside a prefix location refines the match after the outer prefix has been chosen:

NGINX
location /downloads/ {
    root /srv/files;
    location ~ \.iso$ {
        add_header Content-Disposition attachment;
    }
}

Nesting is allowed, but it adds a second matching phase that is easy to misread. Prefer flat locations unless nesting buys real clarity.

root versus alias

Both directives map a URL to a file, but they do it differently, and mixing them up is a classic bug.

  • root appends the whole URI to the directory.
  • alias replaces the matched location prefix with the directory.
NGINX
location /img/ {
    root /data;               # /img/a.png  ->  /data/img/a.png
}
location /img/ {
    alias /data/pics/;        # /img/a.png  ->  /data/pics/a.png
}

The trap with alias is the trailing slash. If the location ends with a slash, the alias must too. Otherwise the replacement glues words together: location /img/ { alias /data/pics; } maps /img/a.png to /data/picsa.png. A related pitfall is a prefix location without a trailing slash: location /img also matches /imgs/secret.txt and /img-old.

try_files

try_files checks a list of candidate paths in order and serves the first one that exists. The last argument is the fallback: a URI for an internal redirect, a named location or a status code such as =404.

NGINX
location / {
    try_files $uri $uri/ /index.html;     # single-page app style
}
location / {
    try_files $uri $uri/ =404;            # plain static site
}

$uri tests for a file at root + URI. $uri/ tests for a directory, and, if it exists, serves its index file. If a directory exists but contains none of the index files, the result is a 403, not a 404. We will use the same directive for front-controller applications in PHP, FastCGI and Application Servers.

The second stand-in computes paths for root, alias and try_files against a small fake file system:

JS root, alias and try_files in numbers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first block shows the missing-slash alias bug in plain numbers. The second shows how the same request behaves under the two fallbacks: a missing page is a 404 on a plain site and an internal redirect to /index.html for a single-page app, while a directory with no index file is a 403 in both cases. The simulation is a model: real Nginx also checks file types, applies index directive settings and handles permissions.

Habits that keep locations simple

  • Start with location / and add exceptions only when needed.
  • Use ^~ for static directories so a broad regex (such as one for .php) never captures files inside them.
  • Put the most important regexes first, since order decides between them.
  • Test a configuration by asking, for each URL you care about, "which location wins and why?", using the five steps.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given location /images/ and location ~* .png$, which handles /images/logo.png?

    Nginx remembers the longest prefix, then tests regexes in order. A matching regex wins unless the prefix has ^~.
  2. 2. What does ^~ do on a prefix location?

    ^~ stops the search after the prefix phase, so regular expressions cannot override that prefix.
  3. 3. How does alias differ from root?

    With location /img/ and alias /data/pics/, /img/a.png maps to /data/pics/a.png. With root /data it would map to /data/img/a.png.
  4. 4. Where can a named location such as @app be reached from?

    Named locations can never be matched by a request URI. try_files and error_page send requests there internally.
  5. 5. In which order are regex locations tested?

    Prefix locations are compared by length, but regexes are tested in file order, and the first match wins.

Summary

  • Locations match the normalized URI path (decoded, slashes collapsed, dot segments resolved, no query string).
  • Algorithm: exact = first; else the longest prefix; if it is ^~ stop; else the first matching regex in file order; else the remembered prefix.
  • Prefix order does not matter, regex order does, and a regex beats a plain prefix.
  • root appends the full URI to a directory; alias replaces the matched prefix, so keep trailing slashes consistent.
  • try_files serves the first existing candidate and ends in a fallback: a URI, a named location or =404.
  • Named locations (@name) are internal targets; keep nesting minimal.

Next: Apache httpd Configuration