Mastering Nginx Regex and Location Matching: Rules, Priorities, and Examples

This article explains Nginx's regular‑expression support, the various location directive prefixes, their matching priorities, and provides concrete configuration examples with code snippets and diagrams to help you correctly route requests in a single‑node Nginx 1.23.2 setup.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Mastering Nginx Regex and Location Matching: Rules, Priorities, and Examples

Introduction: The article validates Nginx v1.23.2 on a single‑node environment, focusing on regular expressions, location path matching rules, and their priority.

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;
    }
}

The following sections are based on this configuration.

1. Nginx Regular Expressions

Nginx follows standard regular‑expression syntax, with the special characters indicating the start of a regex. Regex can be used in server blocks or location directives.

Common Regex Symbols

^  : start of string
$  : end of string
.  : any character except 
 (use [.
] to include newline)
\d : digit
\w : word character (letters, digits, underscore, Chinese characters)
\s : whitespace
\b : word boundary
*  : zero or more of previous token
+  : one or more of previous token
?  : zero or one of previous token (equivalent to {0,1})
{n}   : exactly n repetitions
{n,}  : n or more repetitions
{n,m} : n to m repetitions
[]   : character class, e.g., [a-z]
()   : grouping, e.g., (jpg|gif|swf)
|    : alternation
!    : negation (no logical AND operator)
\    : escape character

Reference: https://www.jb51.net/article/149053.htm

2. Location Path Matching Rules and Priority

The location directive configures request URI handling. Matching proceeds in two stages: first, non‑regex locations are evaluated to find the longest match; then regex locations are checked in definition order.

nginx searches for a non‑regex location with the highest match, then checks regex locations; if a regex matches, it is used, otherwise the previously selected non‑regex location handles the request.

Official priority order (simplified):

1. Exact match with =
2. Longest literal match (including ^~)
3. Regex matches in order of appearance (~* then ~)
4. If no regex matched, use the best literal match.

Priority hierarchy (visualized in the article) can be expressed as:

(location =) > (location full path) > (location ^~) > (location ~*) > (location ~) > (location prefix) > (/)

3. Example Configurations

3.1. Prefix without modifier (case‑sensitive)

server {
    listen 8081;
    server_name 127.0.0.1;
    # No modifier, matches any URI starting with /aaa (case‑sensitive)
    location /aaa {
        default_type text/plain;
        return 200 "access success aaa 
\r";
    }
}

Matches: /aaa, /aaa/, /aaadef, etc. Does not match /Aaa (case‑sensitive).

3.2. Exact match with =

server {
    listen 8081;
    server_name 127.0.0.1;
    # Exact match, case‑sensitive
    location = /bbb {
        default_type text/plain;
        return 200 "access success bbb 
\r";
    }
}

Matches only /bbb (with optional query string). Does not match /bbb/ or different case.

3.3. Regex match (case‑sensitive) with ~

server {
    listen 8081;
    server_name 127.0.0.1;
    # Case‑sensitive regex: starts with /eee and ends with a word character
    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.

3.4. Regex match (case‑insensitive) with ~*

server {
    listen 8081;
    server_name 127.0.0.1;
    # Case‑insensitive regex: starts with /ddd and ends with a word character
    location ~*^/ddd\w$ {
        default_type text/plain;
        return 200 "access success. 111 Regular expression matched: ddd  
\r";
    }
}

Matches /dddb, /dddB, /DDD2, etc.

3.5. Non‑regex with ^~ (higher priority)

server {
    listen 8081;
    server_name 127.0.0.1;
    # ^~ behaves like a plain prefix but stops further searching when matched
    location ^~ /fff {
        default_type text/plain;
        return 200 "access success. Non Regular expression matched: fff  
\r";
    }
}

Matches any URI beginning with /fff (case‑sensitive) and prevents later regex checks.

4. Named Locations

Using @ creates a named location for internal redirects, such as error handling.

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

Additional examples of error_page directives are also shown.

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
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

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.