Master Nginx Regex and Location Matching Rules: How Priority Works

This guide explains Nginx's regular‑expression syntax, the five location prefix types, their matching priority, and provides concrete configuration examples with code snippets and diagrams to help you correctly route requests in a single‑node Nginx v1.23.2 setup.

Liangxu Linux
Liangxu Linux
Liangxu Linux
Master Nginx Regex and Location Matching Rules: How Priority Works

Background and Goal

The article validates how Nginx v1.23.2 processes regular expressions and location path‑matching rules, focusing on priority order. It starts from a minimal server configuration and builds a series of examples to illustrate each rule type.

Basic Server Configuration

server {
    listen 8081;
    server_name 10.90.5.70;

    proxy_connect_timeout 60;
    proxy_read_timeout 600;
    proxy_send_timeout 600;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto "http";
    proxy_set_header Host $host;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_next_upstream error non_idempotent;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";

    location / {
        root /usr/share/nginx/html;
        index index.html index.htm;
    }
}

1. Nginx Regular‑Expression Basics

Nginx follows standard regular‑expression syntax, with the special ~ and ~* prefixes indicating that the following location uses a regex. The article lists common symbols such as ^, $, ., \d, \w, quantifiers * + ? {n} {n,} {n,m}, character classes [], alternation |, and escape \. A reference link is provided for further reading.

2. Location Matching Rules and Priority

The location directive selects a block based on the request URI. Nginx first tries exact matches, then the longest literal prefix, then ^~ prefixes, followed by regular‑expression locations in the order they appear, and finally the generic / block.

location [ = | ~ | ~* | ^~ ] uri { ... }

The official priority sequence is:

Exact match with = (stop searching).

Longest literal string match; if it uses ^~, stop searching.

Regular‑expression matches in configuration order.

If a regex matched, use it; otherwise fall back to the best literal match from step 2.

The article visualises this flow with a diagram (kept below).

Nginx location matching flow
Nginx location matching flow

Location Prefix Types

= uri : exact match; rule applies only when the request URI equals uri.

~ regular : case‑sensitive regex match.

~* regular : case‑insensitive regex match.

^~ uri : literal prefix match that stops further searching (useful to raise priority).

uri (no prefix): standard prefix match.

The relative priority among these types is (=) > (longest literal) > (^~) > (~*) > (~) > (uri) > (/), which the article also expresses as ① > ④ > ③ > ② > ⑤ .

3. Practical Examples

3.1 Prefix without Symbol (case‑sensitive)

server {
    listen 8081;
    server_name 127.0.0.1;
    location /aaa {
        default_type text/plain;
        return 200 "access success aaa 
\r";
    }
}

Matches /aaa, /aaa/, /aaadef, etc., but not /Aaa. Adding a trailing slash to the prefix ( location /aaa/) restricts matches to paths that start with /aaa/.

Prefix match example
Prefix match example

3.2 Exact Match with =

server {
    listen 8081;
    server_name 127.0.0.1;
    location = /bbb {
        default_type text/plain;
        return 200 "access success bbb 
\r";
    }
}

Matches only /bbb (and query strings), not /bbb/ or /bbbcd. Case‑sensitive.

Exact match example
Exact match example

3.3 Regex‑Based Locations

Case‑Sensitive Regex ( ~ )

server {
    listen 8081;
    server_name 127.0.0.1;
    location ~^/eee\w$ {
        default_type text/plain;
        return 200 "access success. 000 Regular expression matched: eee 
\r";
    }
}

Matches /eeeb, /eeeB, /eee2 but not /eee or /eee/.

Case‑sensitive regex example
Case‑sensitive regex example

Case‑Insensitive Regex ( ~* )

server {
    listen 8081;
    server_name 127.0.0.1;
    location ~*^/ddd\w$ {
        default_type text/plain;
        return 200 "access success. 111 Regular expression matched: ddd 
\r";
    }
}

Matches /dddb, /dddB, /DDD2, etc., regardless of case.

Case‑insensitive regex example
Case‑insensitive regex example

3.4 Non‑Regex with ^~ (priority boost)

server {
    listen 8081;
    server_name 127.0.0.1;
    location ^~ /fff {
        default_type text/plain;
        return 200 "access success. Non Regular expression matched: fff 
\r";
    }
}

Matches any URI that starts with /fff (e.g., /fff, /fff/def/) and stops further searching, but not /Fff.

^~ prefix example
^~ prefix example

3.5 Named Locations

Using @ creates an internal named location, useful for error_page or try_files redirections.

# Example: internal redirect for 404 errors
error_page 404 = @fetch;
location @fetch {
    proxy_pass http://fetch;
}

# Typical static error pages
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
    root /usr/share/nginx/html;
}

Conclusion

The article demonstrates that Nginx evaluates location directives in a deterministic order: exact = matches first, then the longest literal prefix (with optional ^~ to halt further checks), followed by regex locations in definition order, and finally the generic /. Understanding these rules enables precise request routing and avoids unexpected matches.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backendregexlocationpriority
Liangxu Linux
Written by

Liangxu Linux

Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.