Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › DevOps

How NGINX Server and Location Block Selection Works

By Freedom251 Team · · 7 min read

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

NGINX makes two separate decisions for every HTTP request. It first selects one server block using the listening address, port, and request host. It then selects one location inside that server by comparing the normalized request URI. A correct location in the wrong server block will never handle the request, and a longer prefix does not automatically defeat a regular-expression location.

The reliable way to predict a result is to follow NGINX’s order: verify the listen socket and host match, normalize the URI, check exact locations, remember the longest prefix, apply ^~ if present, then test regular expressions in configuration order.

As an Amazon Associate I earn from qualifying purchases.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

The two-stage decision NGINX makes

NGINX does not search every server and location directive as one flat list. It performs a server-level selection first and a URI-level selection second.

  1. Server selection: choose a virtual server associated with the request’s listening address and port, then compare the request’s Host value with that server’s server_name values.
  2. Location selection: within the chosen server, compare the normalized URI against its exact, prefix, and regular-expression locations.

This ordering explains a common debugging mistake: changing a location block has no effect when the request is actually entering another virtual host. Always establish the selected server before investigating location precedence.

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

How NGINX chooses the server block

1. The listen address and port narrow the candidates

Each server block is associated with one or more listen addresses and ports. NGINX first considers the servers bound to the address and port that accepted the connection. A server listening on another port cannot receive that request, regardless of how well its server_name matches.

For example, a request accepted on port 443 is evaluated among the HTTPS listeners, not among servers that listen only on port 80. When several blocks share a listener, the host-name rules decide which one wins.

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

2. Host names are tested by priority

Within the selected listener, NGINX evaluates server_name values in this order:

  1. Exact names, such as example.com.
  2. Wildcards beginning with an asterisk, such as *.example.com. If several match, the longest matching wildcard is preferred.
  3. Wildcards ending with an asterisk, such as mail.*. Again, the longest matching wildcard is preferred.
  4. Regular-expression names, evaluated in the order they appear in the configuration. The first matching expression wins.

NGINX stops after the first matching category. A matching exact name therefore prevents wildcard and regular-expression names from being considered. Likewise, once a matching wildcard category has been found, a later category cannot replace it.

3. When no name matches

If the request’s host does not match any configured name for that listener, NGINX uses the default server for the address and port. The default is determined by the listener configuration; do not assume it is the first block you intended to be the fallback. Marking a listener with default_server makes the choice explicit.

HTTP/1.0-style requests or malformed requests may arrive without a Host header. NGINX represents that condition with an empty server name. You can handle it explicitly with server_name "", rather than allowing such traffic to blend into an ordinary named virtual host.

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

Worked server-selection example

server {
    listen 80 default_server;
    server_name _;
}

server {
    listen 80;
    server_name example.com;
}

server {
    listen 80;
    server_name *.example.com;
}

server {
    listen 80;
    server_name ~^user[0-9]+.example.net$;
}

A request for http://example.com/ selects the exact-name server. A request for shop.example.com selects the wildcard server if no longer wildcard matches exist. A host such as user42.example.net can select the regular-expression server. An unmatched host falls through to the listener’s default server.

URI normalization happens before location matching

After selecting the server, NGINX prepares the request URI for comparison. The value used for matching is not necessarily the literal text shown in a browser address bar.

  • Percent-encoded bytes (%XX) are decoded.
  • Dot components such as . and .. are resolved.
  • Adjacent slashes may be compressed.

For troubleshooting, inspect the normalized path that NGINX is matching. A request written with an encoded character or redundant path segment may therefore reach a different location than a simple string comparison suggests.

Query-string arguments are separate from the URI used by location matching. In /search?q=nginx, the location matcher sees the path /search; the ?q=nginx portion does not make a prefix or regular-expression location match.

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

The location-selection algorithm

Step 1: test exact locations

An exact location uses the = modifier:

location = /health {
    return 200 "ok";
}

If the normalized URI is exactly /health, NGINX selects this block and ends the location search immediately. No prefix or regular-expression location can override it. Exact matches are useful for one known URI such as a health endpoint, a robots file, or a deliberately special root path.

Step 2: find the longest matching prefix

NGINX then scans ordinary prefix locations, such as /, /images/, and /images/icons/. It remembers the longest prefix that matches the beginning of the normalized URI.

For /images/icons/menu.svg, all three prefixes might match, but /images/icons/ is the remembered candidate because it is the longest. At this stage, NGINX has not yet decided whether a regular-expression location will take over.

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

Step 3: apply ^~ when the longest prefix has it

The ^~ modifier tells NGINX to use the longest matching prefix immediately and skip regular-expression testing:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
location ^~ /images/ {
    root /srv/www;
}

This is the explicit protection mechanism for a prefix path. If /images/ is the longest match, a later PHP or asset regular expression cannot intercept the request.

Step 4: test regular-expression locations in file order

If the remembered longest prefix does not use ^~, NGINX checks regex locations in the order they appear. The first matching expression wins, even when a plain prefix is longer.

  • ~ performs a case-sensitive match.
  • ~* performs a case-insensitive match.

Because order controls the result, moving one regex above another can change which block receives a request. Put mutually overlapping expressions in an intentional order and keep the patterns as narrow as practical.

Step 5: fall back to the remembered prefix

If no regular-expression location matches, NGINX uses the longest prefix remembered in step 2. If the only matching prefix is /, that root prefix handles the request.

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

Complete example: predicting four requests

server {
    listen 80;
    server_name example.com;

    location = / {
        return 200 "home";
    }

    location ^~ /assets/ {
        root /srv/www;
    }

    location / {
        proxy_pass http://app;
    }

    location ~* .php$ {
        fastcgi_pass unix:/run/php/php-fpm.sock;
    }
}
Request URI Exact match Longest prefix Regex result Selected location Reason
/ = / Not needed Not tested location = / The exact match terminates the search.
/assets/logo.php None ^~ /assets/ Skipped ^~ /assets/ The protected longest prefix prevents the PHP regex from running.
/shop/item.php None / ~* .php$ matches PHP regex A plain prefix is remembered, then the first matching regex overrides it.
/shop/item.css None / No regex matches / The remembered prefix is used as the fallback.

The second and third rows demonstrate the rule that causes most surprises: a longer ordinary prefix does not automatically beat a regex. Only an exact match or a longest prefix marked ^~ can stop regex evaluation before it begins.

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

Choosing the right location form

Form Matches Can a regex override it? Case behavior Best use
location = /path One exact normalized URI No; search ends immediately Literal comparison Health checks, one-off endpoints, or an exact root rule
location /path/ Any URI beginning with the prefix Yes, unless protected by ^~ Prefix comparison Simple path families and readable routing rules
location ^~ /path/ Any URI beginning with the prefix No; regex testing is skipped Prefix comparison Static trees or application areas that must not be intercepted
location ~ pattern First matching case-sensitive expression It is itself a regex candidate Case-sensitive Extensions or patterns where capitalization matters
location ~* pattern First matching case-insensitive expression It is itself a regex candidate Case-insensitive File-extension handling where .PHP and .php should behave alike

Exact and ^~ forms can terminate work early, which makes their behavior and performance easier to reason about. Prefixes are usually the most maintainable choice. Regular expressions are powerful but introduce ordering dependencies and should be reserved for patterns that a simple prefix cannot express.

Why a request reaches the “wrong” virtual host

Check the listener before the names

Confirm the destination IP address and port first. If the request arrives on a different address or port than expected, NGINX will never inspect the server block you edited.

Check the actual Host value

Compare the host sent by the client with the configured exact and wildcard names. Remember that an unmatched host goes to the default server for that listener. To test deliberately from a shell, send a chosen host header while targeting the listener address:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -i http://127.0.0.1/ -H 'Host: example.com'

For HTTPS, also ensure the connection reaches the intended TLS listener; changing only the HTTP host header does not move a request between ports.

Make the fallback explicit

Use listen ... default_server for the intended catch-all block and consider server_name "" when requests without a host header need separate handling. An explicit fallback makes accidental matches easier to identify.

Only then inspect locations

Once the server is confirmed, print the active configuration with your deployment’s normal configuration-dump command and verify the location order. Look for an exact match you forgot, a longer prefix lacking ^~, or an earlier regex that captures the request first. Also compare the normalized URI with the raw URL, especially when percent encoding, dot segments, or repeated slashes are involved.

Common configuration mistakes

  • Assuming the longest prefix always wins: a plain prefix can be replaced by the first matching regex.
  • Adding ^~ to the wrong block: it protects only the longest matching prefix for that request.
  • Ignoring regex order: overlapping expressions are resolved by file order, not by apparent specificity.
  • Testing query strings as part of a location: location matching uses the URI path, not its arguments.
  • Debugging the browser spelling: normalization can change the path before comparison.
  • Editing a server that does not share the listener: server selection occurs before any location rule is considered.

A repeatable prediction checklist

  1. Write down the destination address and port.
  2. List the servers attached to that listener and identify the request’s Host value.
  3. Apply exact, wildcard, and regex server_name priority; if none match, select the default server.
  4. Normalize the URI by accounting for percent escapes, dot segments, and compressed slashes.
  5. Check exact locations first.
  6. Record the longest matching prefix.
  7. If that prefix uses ^~, stop there.
  8. Otherwise test regex locations from top to bottom; select the first match.
  9. If no regex matches, use the remembered longest prefix.

Following these steps turns location selection from trial and error into a deterministic calculation. It also separates two different classes of bugs: the wrong virtual host is a server-selection problem, while the wrong handler inside the right host is a location-selection problem.

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

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.

DevOpsNGINXreverse proxyserver configurationweb servers

Leave a Reply

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

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.

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair 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.