Mastering Nginx Regex and Location Matching Rules: A Practical Guide

This article explains how Nginx processes regular expressions and location directives, details the syntax and priority of different location prefixes, and provides concrete configuration examples with code snippets and diagrams to help developers correctly match request URIs.

Liangxu Linux
Liangxu Linux
Liangxu Linux
Mastering Nginx Regex and Location Matching Rules: A Practical Guide

Introduction

This article demonstrates how Nginx v1.23.2 matches request URIs using regular‑expression and location directives. All examples are based on a minimal server block listening on port 8081.

Regular Expressions in Nginx

Nginx uses standard regular‑expression syntax. The leading modifier ~ (case‑sensitive) or ~* (case‑insensitive) tells Nginx to treat the following pattern as a regular expression.

^   : start of string
$   : end of string
.   : any character except 
 (use [\.
] to include newline)
\d  : digit
\w  : word character (letter, digit, underscore, or Chinese character)
\s  : whitespace
\b  : word boundary
*   : zero or more of previous element
+   : one or more of previous element
?   : zero or one of previous element (equivalent to {0,1})
{n} : exactly n repetitions
{n,}: n or more repetitions
{n,m}: between n and m repetitions
[]  : character class, e.g. [a-z]
()  : grouping, e.g. (jpg|gif|swf)
|   : alternation (OR)
!   : logical NOT (negates following expression)
\\  : escape character

Location Matching Rules and Priority

The location directive determines how Nginx processes a request URI. Matching proceeds in two stages:

All non‑regular‑expression locations are evaluated first; the longest literal match is remembered.

Regular‑expression locations are then tested in the order they appear in the configuration.

Official priority (independent of file order):

1. Exact match with =
2. Longest literal match (including ^~)
3. Regular expressions in definition order (~* then ~)
4. If a regular expression matched, use it; otherwise fall back to the longest literal match.

Five Types of Location Prefixes

= uri : exact match; request URI must be identical to uri.

~ regular : case‑sensitive regular‑expression match.

~* regular : case‑insensitive regular‑expression match.

^~ uri : prefix match that disables further regular‑expression checks.

uri (no prefix): standard prefix match.

Practical Examples

1. Prefix match without a symbol

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, /aaa/def/, /aaa?p1=TOM. Does not match /Aaa (case‑sensitive). Adding a trailing slash ( location /aaa/) restricts matches to paths that contain the slash.

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: /bbb, /bbb?p1=TOM. Does not match /bbb/, /bbbcd, or /Bbb.

3. Case‑sensitive regular expression (~)

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. Does not match /eee, /Eee, /eee/, etc.

4. Case‑insensitive regular expression (~*)

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, /DddH. Does not match /ddd, /Ddd, /ddd/, etc.

5. Prefix match with ^~ (higher priority, non‑regex)

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: /fff, /fff/, /fffdef, /fff/def/, /fff?p1=TOM. Does not match /Fff or /pp/fff. Using location /fff/ would restrict matches to paths that contain the trailing slash.

6. Named locations

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

# Common pattern
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
    root /usr/share/nginx/html;
}

Named locations (prefixed with @) are used internally, for example with error_page or try_files.

Visual Summary

Nginx location matching flow diagram
Nginx location matching flow diagram
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.

BackendConfigurationNGINXWeb serverregexlocation
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.