Nginx Location Matching Explained: Prefix, Regex, and Exact Matches

Your Nginx server block looks right, the config test passes, and still the wrong page loads. A request for /api/users lands on your static site, while /images/logo.png gets handed to PHP-FPM. In most cases the cause is nginx location matching, the set of rules that decides which location block handles each request. Those rules are precise, and they do not work the way most people first guess.

This guide explains the matching order Nginx actually follows, with working examples for each location type and the mistakes that send requests to the wrong block. You can test every example on your own VPS before you deploy it.

How Nginx Location Matching Works

When a request arrives, Nginx first picks a server block using the listen port and server name. Only then does nginx location matching start, looking only at the location blocks inside that server block.

Matching runs against the normalized URI. Nginx decodes percent-encoded characters, resolves . and .. segments, and merges repeated slashes when merge_slashes is on, which is the default. The query string plays no part: /search?q=nginx matches locations as /search. Each request ends up handled by exactly one location block, so the order Nginx checks them in decides everything.

The Four Location Types

Every location block falls into one of four types, set by the modifier in front of the URI pattern. The modifier, not the position in the file, decides which group a block belongs to.

Modifier Match type Example What it does
= Exact match location = / Matches only that exact URI, nothing longer
none Prefix match location /images/ Matches any URI starting with that prefix
^~ Preferential prefix location ^~ /static/ Prefix match that skips regex checking if it is the longest match
~ Case-sensitive regex location ~ .php$ Matches URIs against a regular expression, case-sensitive
~* Case-insensitive regex location ~* .(jpg|png|css)$ Same as ~, but ignores letter case

The Matching Order, Step by Step

The nginx location block priority follows a fixed order. Learn it once and most routing surprises disappear.

  1. Exact match first. If a location = /some/path matches the URI exactly, Nginx uses it and stops looking.
  2. Longest prefix match. Nginx compares all plain and ^~ prefix locations and remembers the longest one that matches.
  3. ^~ short-circuits the search. If that longest prefix uses ^~, Nginx uses it immediately and never checks regex locations.
  4. Regex locations, in file order. Nginx tests regex locations from top to bottom and uses the first one that matches.
  5. Fallback to the longest prefix. If no regex matches, the longest prefix from step 2 handles the request.

In practice, a regex location does not beat a prefix location just because it looks more specific. The prefix is remembered first, and the regex only gets a chance when the winning prefix is not marked ^~. Among regex locations, order in the file is the tiebreaker: two regexes that both match a URI resolve to whichever appears first.

server {
    listen 80;
    server_name example.com;
    root /var/www/example.com;

    location = / {
        try_files /index.html =404;
    }

    location / {
        try_files $uri $uri/ =404;
    }

    location /images/ {
        expires 30d;
    }

    location ~ .php$ {
        include fastcgi_params;
        fastcgi_pass unix:/run/php/php8.4-fpm.sock;
    }
}

In this config, a request for /images/logo.png matches the prefix /images/ and the regex .(jpg|png)$ is not present, so the prefix wins. A request for /index.php matches the prefix / and then the regex .php$, so PHP-FPM handles it. A request for / hits the exact match and stops there.

Prefix Locations and the ^~ Modifier

An nginx prefix location matches the start of the URI, so location /blog/ matches /blog/, /blog/first-post, and /blog/anything/deeper. When several prefixes match, the longest one wins: /blog/images/ beats /blog/ for a request under /blog/images/. This is the part people usually get right.

The part people miss is ^~. Marking a prefix with ^~ tells Nginx to skip regex checking entirely when that prefix is the longest match. That makes it the right tool for directories you always want served directly from disk, such as /static/ or /uploads/, where a stray regex could otherwise grab the request and send it to PHP. If you are still sketching out your server blocks, the walkthrough on setting up Nginx server blocks on Ubuntu 24.04 covers how these blocks fit together in a full config.

The risk runs the other way too: ^~ on a broad prefix such as location ^~ / silences every regex under it, including the PHP handler. Use ^~ on narrow directories only, and check the result with a real request afterward. For a deeper look at how these rules interact, see the companion guide on how Nginx location block priority really works.

Regex Locations: ~ and ~*

Regex locations match anywhere in the URI, not just at the start, which makes them flexible and easy to get wrong. location ~ .php$ matches any URI ending in .php, at any depth. The ~* variant ignores case, so location ~* .(jpg|jpeg|png|gif)$ also matches /Photo.JPG, which the case-sensitive version would miss. That detail matters on sites where users upload files with unpredictable casing.

Because regex locations are checked in file order, put the more specific pattern first. A general pattern such as ~ .(css|js)$ placed above a specific one like ~ ^/admin/.*.css$ will swallow the admin request before the specific rule ever runs. Keep the regex list short: every request that survives the prefix stage walks this list. Regex locations are also the usual place to block unwanted traffic, and the guide on blocking bad bots with Nginx rate limiting shows how a regex location pairs with limits to slow scrapers down.

Exact Matches and When to Use Them

An exact match only fires when the URI is identical, character for character. location = /health matches /health and nothing else: not /health/, not /health/check. That precision is the point. Use exact matches for single endpoints where any other behavior would be wrong, such as a health check your monitor pings, a favicon.ico you want served with no logging, or the site root.

The root deserves a warning. location = / matches only the bare homepage request, while location / matches every URI on the site and acts as the fallback prefix. Mixing the two up is a common source of confusion: people add location = / expecting it to change routing for the whole site, then wonder why nothing else changed. It changed exactly one URI, which is what it is for. Because an exact match wins immediately, it also skips the rest of the nginx location order, so a request that hits one never reaches your regex rules.

Common Mistakes That Send Requests to the Wrong Block

  1. Regex order is backwards. A broad regex above a narrow one wins every time. Read your regex locations top to bottom and ask whether each one could steal requests meant for the ones below it.
  2. ^~ on a prefix that is too broad. It silences every regex under that prefix, including the PHP handler. If PHP files suddenly download as text after a config change, check for a stray ^~ first.
  3. Trailing slash confusion. location /api/ matches /api/users but not /api with no slash. If your API client calls the bare path, that request falls through to location / instead.
  4. Putting app logic in location /. That block is the fallback for everything unmatched, so directives there run for requests you never thought about, including bots probing odd paths. Keep it minimal and route real app paths explicitly.
  5. Using if inside a location block for routing. The if directive inside location blocks behaves unpredictably in Nginx and can produce results that change between versions. Use separate location blocks or map instead.

Testing Your Location Blocks Safely

Never edit a live config and hope. Run nginx -t to check syntax, then nginx -T to dump the full effective config and confirm the file you edited is the one Nginx actually loads. Then test with real requests: curl -I https://example.com/images/logo.png shows which block answered, and repeating the test for a PHP path and the root covers the branches that matter.

When a test surprises you, add a temporary add_header X-Location "images-block"; inside the suspect block, reload, and curl again. The header tells you exactly which block handled the request, which beats guessing from the response body. Remove the header before you finish. The full safe-change routine, including how to reload without dropping connections, is covered in the guide on testing a new Nginx config without taking your site down.

If you remember one thing, remember the order: exact match first, longest prefix second, regex third unless ^~ stops the search. Write your blocks with that order in mind, test each branch with curl, and the wrong-page mystery mostly goes away.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.