iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
Antihost offers Linux VPS plans with full root access, unlimited traffic on a 1 Gbps port and a 14-day free trial.
The NGINX location directive decides which configuration handles each request URI. NGINX first looks for an exact match, then records the longest matching prefix, optionally evaluates regular expressions, and finally uses the remembered prefix when no regex wins. An exact location = ends the search immediately; ^~ prevents regex locations from taking over a prefix subtree; otherwise the first matching regex in configuration order wins.
What the NGINX location directive does
A location block groups directives that should apply to a particular request path. Those directives might serve files, proxy traffic to an application, rewrite a URI, return a status, or set headers. The block is selected by comparing the request URI with the location modifiers and patterns in the active server block.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Location selection is separate from the directives that run after selection. For example, try_files, proxy_pass, and root do not decide which location wins; they operate inside the location NGINX has selected. A rewrite using last can change that result by starting a new location search.
NGINX location precedence, step by step
- Check exact locations. A location beginning with
=must match the complete URI. If it matches, NGINX stops searching and uses that block. - Find prefix matches. Locations without a regular-expression modifier are compared as prefixes. NGINX remembers the longest matching prefix.
- Honor
^~. If the longest prefix has the^~modifier, NGINX skips every regular-expression location and uses that prefix. - Check regular expressions. Without
^~, NGINX tests regex locations in the order they appear in the configuration. The first matching regex wins, even when a longer ordinary prefix also matched. - Fall back to the remembered prefix. If no regex matches, the longest prefix selected in step two handles the request.
This explains a common surprise: a regex location can override a plain prefix that appears more specific, because regex evaluation occurs after prefix scanning. The ^~ modifier is the explicit way to protect a prefix tree from that override.
#1 Best Overall
- B5 Recipe Book: This hardcover blank recipe book measures 10''×7.3'', containing 150 blank pages, comes with 1 sheet of DIY category stickers, perfect for writing down your own recipes and organizing them in one place.
- Practical Layout - 5 pages of conversion charts show you everything you'll ever need to know in the kitchen. The table of contents will help organize your personal favorite recipes. A back pocket is designed for loose items.
- Easy to Use - This blank cookbook is made of high-quality paper with a beautiful hardcover for long-term use. The sturdy gold double-wire spiral binding makes writing easier and page turning smoother.
- Make Your Own Recipes - This blank cookbook has up to 150 blank pages for you to write in your own recipes, with plenty of space to record ingredients and instructions. You can write down all the special tips for your family members.
- Thoughtful Gift - A personalized recipe book makes a thoughtful gift for your children or newlyweds, and a great gift for housewarming, weddings, bridal showers, anniversaries, or any other occasion.
Location modifiers and their exact behavior
| Syntax | Matching rule | Regex evaluation | Typical use |
|---|---|---|---|
location = /path |
Exact URI only | Search ends immediately on a match | Health checks, robots.txt, a single callback, or another unique endpoint |
location /path/ |
Ordinary prefix | Regex locations may override it | General application or directory routing |
location ^~ /path/ |
Longest prefix | Matching regex locations are skipped | Static trees or API subtrees that must not be intercepted |
location ~ pattern |
Case-sensitive regular expression | First matching regex in file order wins | Extensions or filename patterns where case matters |
location ~* pattern |
Case-insensitive regular expression | First matching regex in file order wins | Image extensions or other case-insensitive filenames |
The regular-expression modifiers apply only to regex locations. A plain prefix such as /images/ is not a regex, so characters such as a period have no special pattern meaning there.
A complete configuration example
server {
# Exact match: only /health
location = /health {
return 200 "okn";
}
# Longest prefix; regex locations cannot override this subtree
location ^~ /assets/ {
root /srv/www;
}
# Case-sensitive PHP extension match
location ~ .php$ {
proxy_pass http://php_backend;
}
# Case-insensitive image extension match
location ~* .(jpg|jpeg|png|gif)$ {
root /srv/images;
}
# General fallback prefix
location / {
proxy_pass http://app_backend;
}
}
In this example, the exact health endpoint wins before any prefix or regex is considered. Requests below /assets/ use the ^~ block, so an image filename under that tree does not reach the image regex. A PHP-looking URI outside that tree can reach the case-sensitive regex. Everything else falls through to the application proxy.
Worked request outcomes
| Request URI | Selected location | Reason |
|---|---|---|
/health |
location = /health |
The complete URI matches an exact location, which terminates the search. |
/assets/logo.jpg |
location ^~ /assets/ |
The protected prefix matches and suppresses regex evaluation. |
/images/photo.jpg |
The image regex, if present and matching | The ordinary /images/ prefix is remembered, then the regex is tested and can take precedence. |
/images/photo.gif |
The ordinary /images/ prefix when no regex matches |
NGINX falls back to the longest remembered prefix. |
Choosing between root, alias, and try_files
Using root
root appends the request URI to the configured filesystem path. With location /static/ { root /srv/site; }, a request for /static/app.css is mapped beneath /srv/site/static/app.css. This behavior is convenient when the URI path mirrors the directory layout.
Using alias
alias replaces the part of the URI matched by the location with a filesystem path. For a directory location, keep the trailing slash convention consistent:
location /static/ {
alias /srv/site/static/;
try_files $uri $uri/ =404;
}
With alias, verify the resulting URI-to-file mapping rather than assuming it behaves like root. A missing or extra slash can point NGINX at a different path than intended. Use a prefix location for a whole directory tree; choose a regex location only when the selection genuinely depends on a filename pattern.
Using try_files
try_files checks candidates in the order written. It tests files or directories, then internally redirects to a URI or returns the specified status when no candidate exists. In the example above, NGINX checks the requested path, then a directory form, and returns 404 if neither exists. Keep the final fallback explicit so missing assets do not silently become application requests.
Free tools Windows power users keep installed
One-click scans. No signup required.
Reverse proxy locations
A common layout sends application traffic through a general prefix while handling selected assets separately:
server {
location / {
proxy_pass http://app_backend;
}
location ~* .(jpg|jpeg|png|gif)$ {
root /srv/images;
}
}
Because / is an ordinary prefix, the image regex can win for matching filenames. If the application owns a subtree that must never be intercepted, give that subtree a ^~ prefix, for example location ^~ /uploads/. Place a regex location after it or elsewhere in the file; the modifier, not visual order against prefixes, is what suppresses regex evaluation for that subtree.
When using proxy_pass, remember that the proxy directive runs only after location selection. A request reaching the wrong block is therefore a matching problem first, not a proxy-backend problem. Inspect the URI and the modifiers before changing upstream settings.
Rewrites: when location selection starts again
Rewrite directives execute sequentially. A rewrite with the last flag changes the URI and triggers a new location search, so the request may enter a different block. A rewrite with break changes processing while remaining in the current location. This distinction matters when a rewrite appears to be ignored: the rewritten URI may be selecting another location, or a break may intentionally prevent a second search.
Rank #2
- Create a Culinary Legacy: The Pipilo Press Blank Family Cookbook Recipe Binder offers a timeless platform for chronicling beloved recipes. With its hardcover and spiral binding, this recipe book to write in your own recipes ensures durability and ease of use for generations
- Thoughtful Gifting Choice: This book for writing recipes is an ideal present for various occasions, adding a personal touch to celebrations. Its elegant design makes it perfect for moms cookbook DIY projects or anyone passionate about preserving family traditions
- Durable Design Features: Constructed with a 300gsm cardstock cover and matte lamination, this cookbook you can write in ensures longevity. Its spiral-bound format provides convenient access to pages, making it a practical tool for everyday use
- Organized Recipe Storage: The included memo pocket offers a space to store handwritten notes or recipe cards, enhancing its functionality. This feature transforms the recipe book for moms into a sentimental family memento
- Ample Writing Space: Measuring 6.5 x 8.2 inches, this blank spiral family recipe cookbook offers plenty of room for detailed notes. It is perfect for jotting down ingredients, preparation methods, and serving suggestions for a complete culinary record
location /old/ {
rewrite ^/old/(.*)$ /new/$1 last;
}
location /new/ {
proxy_pass http://app_backend;
}
Here, a request under /old/ is rewritten and then evaluated against the available locations again. If the directive used break instead, processing would continue inside the original block.
Why an NGINX location block is being ignored
The URI is not the one you think
Check the actual request path, including a leading slash, extension, and letter case. Query strings are not part of the URI used for location matching, so a condition that appears to depend on a query parameter cannot be implemented by a normal path location alone.
An exact location wins first
A matching location = prevents every broader rule from running. Remove or narrow an unintended exact block if a request always lands there.
A regex is winning over a prefix
If an ordinary prefix and a regex both match, the regex is tested after prefix scanning and can win. Convert the prefix to ^~ when that subtree must be handled by the prefix, or adjust the regex so it no longer matches those URIs.
A different regex appears earlier
Regex locations use configuration order and the first match wins. Two overlapping ~ or ~* blocks can therefore produce a result that seems unrelated to their apparent specificity. Put the intended rule first and make patterns mutually exclusive where possible.
Case sensitivity differs
~ treats case as significant, while ~* ignores case. A request for PHOTO.JPG will not match a lowercase-only pattern under ~ unless the expression accounts for it.
A rewrite caused a second search
Trace every rewrite and its flag. last starts location selection again with the new URI; break stays in the current location. The block you inspect in the file may not be the block handling the rewritten request.
Filesystem mapping is wrong, not matching
Once the intended location is confirmed, inspect root versus alias, trailing slashes, and the candidate order in try_files. A correct match can still produce a 404 when the computed filesystem path is incorrect.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →A practical design method
- Start with exact endpoints that need unambiguous behavior, such as a health check.
- Add protected directory prefixes with
^~when regex rules must not intercept them. - Add regex locations only for real pattern-based requirements, such as extensions, and decide explicitly whether case matters.
- Define one ordinary prefix as the application fallback.
- For static content, choose
rootwhen URI and directory structure align; choosealiaswhen the URI should map to a different directory. - Use
try_fileswith an explicit final URI or status so missing files have predictable behavior. - Review rewrites separately, noting which ones use
lastand therefore perform another location lookup.
Location-selection checklist
- Is there an exact match that terminates the search?
- Which ordinary prefix is the longest match?
- Does that prefix use
^~? - If regex evaluation is allowed, which regex appears first and matches?
- Are you using
~or~*intentionally? - After selection, does
rootoraliasproduce the expected path? - Does
try_filestest candidates in the required order? - Does a rewrite with
lastsend the request into a different location?
Key takeaway
Think of NGINX location matching as two passes: exact and prefix discovery first, then optional regex evaluation. Exact matches stop immediately; the longest ^~ prefix blocks regex overrides; otherwise the first matching regex in file order wins, with the longest prefix as the final fallback. Once that order is clear, most “ignored location” problems can be resolved by inspecting modifiers, regex order, URI case, rewrites, and filesystem mapping in that sequence.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

