Understanding Nginx location Directive: Syntax, Modifiers, and Matching Order
This article explains the Nginx location directive syntax, the four optional modifiers (=, ~, ~*, ^~), their matching behavior, the overall location matching order, and provides practical configuration examples to help beginners correctly configure Nginx routing.
Nginx, a high‑performance reverse proxy server, uses the location block inside the http context to direct requests based on URI patterns. The basic syntax is location [=|~|~*|^~] uri { … } , where the optional modifiers change how the URI is matched.
Four optional modifiers :
= – exact match; if the request URI exactly equals the specified string, processing stops.
~ – case‑sensitive regular‑expression match.
~* – case‑insensitive regular‑expression match.
^~ – prefix (standard) match that disables further regular‑expression checks.
When a regular expression is used, the ~ or ~* modifier must be present; adding ! before them ( !~ , !~* ) negates the match.
Location matching order without modifiers follows these steps:
Search for the most specific standard URI match (longest prefix).
If a regular‑expression location matches, it is chosen immediately; otherwise, the best standard match is used.
When modifiers are present, the overall precedence is:
( location = ) → ( location (full path) ) → ( location ^~ ) → ( location ~ and location ~* in source order) → ( location (prefix) ) → ( location / ).
Practical examples illustrate each modifier:
location = /login {
# exact match for /login, stop processing
} location ~ /images/ {
# case‑sensitive regex match, stop after match
} location ~* /images/ {
# case‑insensitive regex match, stop after match
} location ^~ /images/ {
# prefix match, skip further regex checks
} location /blog/ {
# longest prefix match, order‑independent
}A comprehensive case study lists several location blocks (exact, prefix, regex, and catch‑all) and shows which rule is selected for various request URLs such as http://www.findme.wang/ , /login , /login.html , and /blog/detail/3.html .
The article concludes that understanding these modifiers and matching precedence is essential for correctly configuring Nginx routing and avoiding unexpected request handling.
360 Tech Engineering
Official tech channel of 360, building the most professional technology aggregation platform for the brand.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.