The NGINX location directive decides which configuration handles a request URI. NGINX checks exact and prefix locations first, remembers the longest matching prefix, then tests regular expressions unless that prefix uses ^~. The first matching regular expression wins; if none matches, NGINX falls back to the remembered prefix. An exact = match ends the search immediately.
Antihost offers Linux VPS plans with full root access, unlimited traffic on a 1 Gbps port and a 14-day free trial.
That order explains most “ignored location” problems. A regex can override an ordinary prefix, but it cannot override a matching ^~ prefix. The examples below show how to predict the winning block, map static files safely, combine assets with a reverse proxy, and avoid rewrite loops.
As an Amazon Associate I earn from qualifying purchases.
Recommended Free Tools
What the NGINX location directive does
A location block associates a URI pattern with request handling instructions. Inside it you might serve files with root or alias, forward traffic with proxy_pass, return a status directly, or apply rewrites. The directive does not select a block by the order in which blocks appear as a whole. NGINX follows a defined matching algorithm, and different location modifiers change that algorithm.
Matching is performed against the request URI, not the full URL. The scheme, host name, and query string are not what determine the location. A request such as /images/photo.jpg?size=large is matched using the path /images/photo.jpg; the query string does not make a separate location pattern.
#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.
“To find the location that best matches a URI, NGINX Plus first compares the URI to the locations with a prefix string.” — NGINX, Configuring NGINX and NGINX Plus as a Web Server
NGINX location precedence, step by step
- Check exact and prefix locations. An exact location uses
=. Prefix locations have no modifier or use^~. NGINX records the longest prefix that matches the URI. - Stop immediately for an exact match. If
location = /healthmatches, no regular expression or broader prefix can replace it. - Decide whether regular expressions are allowed. If the remembered longest prefix has the
^~modifier, NGINX skips every regular-expression location. - Evaluate regular expressions in file order. Locations using
~or~*are tested in the order they appear in the configuration. The first matching expression wins, even when a longer ordinary prefix also matched earlier. - Use the remembered prefix when no regex matches. If regular-expression testing is skipped or no expression matches, NGINX processes the longest prefix location it found.
In practical terms, an exact match has the highest priority, a ^~ prefix protects its subtree from regex interception, and an ordinary prefix is a fallback that remains vulnerable to a matching regex.
Free tools Windows power users keep installed
One-click scans. No signup required.
Location syntax and what each modifier means
| Syntax | Matching behavior | Typical use | Important limitation |
|---|---|---|---|
location = /path |
Exact URI only | Health checks, one special endpoint | Does not match child paths such as /path/extra |
location /path/ |
Case-sensitive prefix | General directory or application subtree | A regex can take precedence after prefix scanning |
location ^~ /path/ |
Longest prefix, with regex evaluation disabled for this match | Static trees or protected subtrees | It is still a prefix, not an exact match |
location ~ .php$ |
Case-sensitive regular expression | Filename or extension rules | First matching regex in configuration order wins |
location ~* .(jpg|jpeg|png|gif)$ |
Case-insensitive regular expression | Image extensions regardless of case | Can override an ordinary prefix unless that prefix is ^~ |
The distinction between ~ and ~* is only case sensitivity. A case-sensitive expression ending in .jpg$ does not match PHOTO.JPG; the case-insensitive form can.
Exact, prefix, and regex examples
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 regex; first matching regex in file order wins
location ~ .php$ {
proxy_pass http://php_backend;
}
# Case-insensitive image regex
location ~* .(jpg|jpeg|png|gif)$ {
root /srv/images;
}
# General fallback prefix
location / {
proxy_pass http://app_backend;
}
}
/health selects the exact block and returns immediately. A request for /assets/logo.jpg selects the ^~ /assets/ prefix; the image regex is never considered. A request for /images/photo.jpg can be caught by the image regex because /images/, if present as an ordinary prefix, does not prevent regex evaluation. A request for an extension that matches no regex falls back to the longest prefix, often location /.
Worked request outcomes
| Request URI | Candidate locations | Winning location | Reason |
|---|---|---|---|
/health |
= /health, / |
= /health |
Exact matching terminates the search. |
/assets/logo.jpg |
^~ /assets/, image regex, / |
^~ /assets/ |
The longest prefix is marked ^~, so regex locations are skipped. |
/images/photo.jpg |
/images/, image regex, / |
Image regex | The ordinary prefix is remembered, then the matching regex is tested. |
/images/photo.gif |
/images/, no matching regex |
/images/ |
No regex wins, so NGINX uses the remembered prefix. |
How to reason about a location that appears to be ignored
Check for an exact match first
An exact block can make a broader rule look ineffective because it always wins for that one URI. Confirm that the request path is exactly the string in the block. A trailing slash or an additional path segment changes the URI and therefore changes the match.
Find the longest prefix
List every ordinary and ^~ prefix that begins with the request path. NGINX remembers only the longest one. A shorter prefix cannot become the final fallback when a longer prefix exists.
Look for a regex that wins afterward
If the longest prefix is ordinary, inspect all ~ and ~* blocks. They are not ranked by apparent specificity or by prefix length. They are tested in configuration order, and the first expression that matches takes control.
Check whether ^~ intentionally blocks the regex
When a regex seems not to run, the cause may be deliberate: a matching ^~ prefix disables regex evaluation for that request. Move or remove the modifier only if regex handling is actually required for that subtree.
Verify the URI used after a rewrite
Rewrite directives execute sequentially. A rewrite with last changes the URI and starts a new location search, so the request can enter a different block. A rewrite with break continues processing in the current location. If a rewritten request lands in an unexpected block, trace the URI after each rewrite and distinguish a new search from continued processing.
Serving static files: root, alias, and try_files
root appends the URI
With root, NGINX appends the request URI to the configured filesystem path. For example, with root /srv/www;, a request for /assets/logo.svg is looked up beneath the root using that URI path. This behavior is convenient when the URL tree mirrors the directory tree.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitchesRank #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
alias replaces the matching location
alias maps the matching location to a replacement filesystem path instead of simply appending the complete URI. Because the matched prefix is replaced, check how slashes line up between the location and alias values. A missing or extra trailing slash can produce a filesystem path different from the one intended.
Use try_files for ordered candidates
try_files tests files or directories in the order listed. If a candidate exists, processing continues with that result. If none exists, the final argument can be a URI for an internal redirect or an explicit status such as =404.
location /static/ {
alias /srv/site/static/;
try_files $uri $uri/ =404;
}
This pattern handles a static directory and returns a 404 when neither the requested file nor directory exists. Use a prefix location for a directory tree. Use a regex location only when selection genuinely depends on a filename pattern, and remember that a ^~ asset prefix can intentionally prevent a regex asset rule from taking over.
Combining static locations with a reverse proxy
A common server layout sends application traffic to an upstream while handling selected files locally:
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →server {
location ^~ /assets/ {
root /srv/www;
}
location ~* .(jpg|jpeg|png|gif)$ {
root /srv/images;
}
location / {
proxy_pass http://app_backend;
}
}
In this arrangement, requests under /assets/ stay in the protected prefix, image-looking requests elsewhere can be handled by the case-insensitive regex, and everything else reaches the application proxy. If the asset prefix were written without ^~, a matching image regex could intercept an image beneath that directory.
Keep the location decision separate from upstream behavior: first determine which block wins, then inspect directives such as proxy_pass, root, or alias inside that block. Debugging the upstream before confirming the selected location often sends the investigation in the wrong direction.
Rewrites and a second location search
Rewrites can change the URI that NGINX is processing. With last, NGINX performs a new location lookup against the changed URI, so exact, prefix, and regex precedence is applied again. With break, processing remains in the current location. This difference matters when a rewrite appears to “skip” directives: the directives may belong to the original block, while last has moved the request into another one.
- Record the original request URI.
- Apply rewrite directives in their listed sequence.
- For
last, run the complete location-selection algorithm again using the new URI. - For
break, continue with the current location’s remaining processing.
When several rewrites are involved, make each intermediate URI explicit in comments or operational notes. This prevents accidental loops and makes it clear which block is expected to handle the final URI.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallA practical method for designing location blocks
- Declare one-off endpoints as exact matches. Use
location =when only one URI should receive special handling. - Choose a prefix for a subtree. Use an ordinary prefix for a directory or application area that may still need regex handling.
- Add
^~when the subtree must be authoritative. This is useful when local static handling must not be intercepted by extension rules. - Use regex only for pattern-dependent selection. File extensions and naming patterns are suitable; a directory tree is usually clearer as a prefix.
- Order regex locations deliberately. Since the first matching regex wins, place the intended exception before broader expressions.
- Choose filesystem mapping consciously. Use
rootwhen the URI should be appended; usealiaswhen the location prefix should be replaced. - Define the missing-file result. With
try_files, decide whether failure should internally redirect or return a status such as=404. - Document rewrite control flow. Mark where
laststarts a fresh location search and wherebreakstays in place.
Common configuration pitfalls
- Expecting a longer prefix to beat a regex. Length matters when choosing the remembered prefix, but an ordinary prefix does not automatically defeat regex evaluation.
- Assuming regex locations are globally ranked. They are evaluated in file order, not by expression length or perceived precision.
- Using
^~without realizing its consequence. It protects the prefix by skipping all regex locations, including one you may have intended to use. - Confusing
rootandalias. Their URI-to-filesystem mapping differs, and slash consistency is especially important withalias. - Forgetting case behavior.
~is case-sensitive;~*is case-insensitive. - Debugging the wrong URI after a rewrite. A
lastrewrite invokes a new search, so the final block may have no obvious relationship to the original one.
Quick decision checklist
- Is the requested URI an exact match?
- Which prefix is longest?
- Does that prefix use
^~? - If not, which regex appears first and matches?
- If no regex matches, what directives are in the remembered prefix?
- Does the block use
rootoralias, and does the resulting path have the expected slashes? - Does
try_filestest the candidates in the intended order? - Did a rewrite use
lastand start another location search, orbreakand remain in the current block?
Answering those questions in order gives a deterministic explanation for the selected block. The location directive is not a “first block wins” feature: exact matching, longest-prefix memory, optional regex evaluation, regex file order, and rewrite behavior together determine the result.
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.




