Backend Development 13 min read

Master Nginx Regex and Location Matching: Rules, Priorities, and Practical Examples

This article demonstrates how Nginx v1.23.2 processes regular expressions and location directives, explains the matching hierarchy and priority rules, and provides concrete configuration examples—including exact, prefix, and regex‑based locations—so readers can reliably control URL routing in their servers.

Raymond Ops
Raymond Ops
Raymond Ops
Master Nginx Regex and Location Matching: Rules, Priorities, and Practical Examples

This article verifies Nginx v1.23.2 regular‑expression and location‑matching rules in a single‑node environment.

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 Expressions

Nginx follows the standard regular‑expression syntax, with the special character

~

indicating that the following pattern should be interpreted as a regular expression. Regular expressions can be used in the

server

block or within

location

directives.

Common regex symbols

^  : match start of string
$  : match end of string
.  : match any single character except 

\d : match digits
\w : match letters, digits, underscore, or Chinese characters
\s : match whitespace
\b : match word boundary
*  : match preceding element zero or more times
+  : match preceding element one or more times
?  : match preceding element zero or one time
{n}   : repeat n times
{n,}  : repeat n or more times
{n,m} : repeat n to m times
[]   : character class
[c]  : match character c
[a-z] : match any lowercase letter
[a-zA-Z0-9] : match alphanumeric characters
()   : group
|    : alternation
!    : negation (applies to following expression)
\    : escape character

2. Location Path Matching Rules and Priority

The

location

directive determines how Nginx handles a request URI. Matching proceeds in a defined order, first considering non‑regex locations, then regex locations, and finally applying the best match according to priority.

Location matching syntax

Syntax:

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

When searching for a matching

location

, Nginx first evaluates locations without regular expressions, selects the longest matching prefix, then checks regular‑expression locations. If a regex matches, it is used; otherwise the previously selected non‑regex location handles the request.

nginx first matches locations without regex, selects the longest match, then checks regex locations. If a regex matches, it is used; otherwise the previously selected non‑regex location handles the request.

Official priority rules

1. Directives with the = prefix (exact match) – stop searching.
2. All remaining conventional strings – longest match first; if the match uses ^~, stop searching.
3. Regular expressions – in order of definition.
4. If a regex matched, use it; otherwise use the match from step 2.

Location prefix categories

= uri – exact match; case‑sensitive; request must match the URI exactly.

~ regular – case‑sensitive regular‑expression match.

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

^~ uri – non‑regex prefix; if matched, stop further searching (higher priority).

uri – plain prefix match without any modifier.

Example configurations

1) Prefix without modifier (case‑sensitive):

server {
    listen 8081;
    server_name 127.0.0.1;
    # location /aaa matches /aaa, /aaa/, /aaadef, /aaa/def/, etc.
    location /aaa {
        default_type text/plain;
        return 200 "access success aaa 
\r";
    }
}

2) Exact match with = (no regex):

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

3) Case‑sensitive regex match with ~:

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

4) Case‑insensitive regex match with ~*:

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

5) Prefix with ^~ (higher priority, no 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";
    }
}

6) Named location using @ (for internal redirects such as error_page):

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

Matching flow diagram

Nginx matching flow diagram
Nginx matching flow diagram

The diagram illustrates the step‑by‑step process: check for exact = matches, then evaluate longest prefix matches (including ^~), then test regular‑expression locations in order, and finally fall back to the best non‑regex match.

BackendConfigurationNginxweb serverregexlocationurl-matching
Raymond Ops
Written by

Raymond Ops

Linux ops automation, cloud-native, Kubernetes, SRE, DevOps, Python, Golang and related tech discussions.

0 followers
Reader feedback

How this landed with the community

login 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.