Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk8 min

Nginx Location Directive Explained With Examples

A practical guide to NGINX location precedence: exact matches, longest prefixes, ^~ protection, regex order, static-file mapping, reverse proxies, rewrites, and fixes for ignored location blocks.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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
Recipe Book to Write in Your Own Recipes, Spiral Blank Cookbook 150 Recipes
  • 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

  1. 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.
  2. Stop immediately for an exact match. If location = /health matches, no regular expression or broader prefix can replace it.
  3. Decide whether regular expressions are allowed. If the remembered longest prefix has the ^~ modifier, NGINX skips every regular-expression location.
  4. 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.
  5. 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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Pipilo Press Blank Family Cookbook Recipe Binder - 6.5 x 8.2 in Hardcover Spiral Bound - 90 Ruled Pages with Memo Pocket - Write In Your Own Recipes & Meal Planning Notebook
  • 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.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Combining static locations with a reverse proxy

A common server layout sends application traffic to an upstream while handling selected files locally:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

  1. Record the original request URI.
  2. Apply rewrite directives in their listed sequence.
  3. For last, run the complete location-selection algorithm again using the new URI.
  4. 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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A practical method for designing location blocks

  1. Declare one-off endpoints as exact matches. Use location = when only one URI should receive special handling.
  2. Choose a prefix for a subtree. Use an ordinary prefix for a directory or application area that may still need regex handling.
  3. Add ^~ when the subtree must be authoritative. This is useful when local static handling must not be intercepted by extension rules.
  4. Use regex only for pattern-dependent selection. File extensions and naming patterns are suitable; a directory tree is usually clearer as a prefix.
  5. Order regex locations deliberately. Since the first matching regex wins, place the intended exception before broader expressions.
  6. Choose filesystem mapping consciously. Use root when the URI should be appended; use alias when the location prefix should be replaced.
  7. Define the missing-file result. With try_files, decide whether failure should internally redirect or return a status such as =404.
  8. Document rewrite control flow. Mark where last starts a fresh location search and where break stays 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 root and alias. Their URI-to-filesystem mapping differs, and slash consistency is especially important with alias.
  • Forgetting case behavior. ~ is case-sensitive; ~* is case-insensitive.
  • Debugging the wrong URI after a rewrite. A last rewrite 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 root or alias, and does the resulting path have the expected slashes?
  • Does try_files test the candidates in the intended order?
  • Did a rewrite use last and start another location search, or break and 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.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.