NGINX makes two separate decisions for every HTTP request: it first selects a virtual server using the listen address, port, and Host name; it then selects one location block using the normalized request URI. A correct location in the wrong server block can never handle the request. Within the selected server, an exact = location ends the search, the longest prefix is remembered, ^~ can prevent regular-expression checks, and otherwise the first matching regex in configuration order wins.
Antihost offers Linux VPS plans with full root access, unlimited traffic on a 1 Gbps port and a 14-day free trial.
The two-stage request decision
It is useful to treat NGINX routing as two different selectors rather than one large search. The first selector chooses a server block. The second selector chooses a location inside that server. The second stage cannot repair a mistake in the first stage: if the request landed in another virtual server, none of the locations in the intended server are considered.
As an Amazon Associate I earn from qualifying purchases.
Free tools Windows power users keep installed
One-click scans. No signup required.
- Server selection: NGINX uses the listening address and port, then compares the request host with
server_namevalues. - URI normalization: NGINX prepares the request URI before comparing it with locations.
- Location selection: NGINX evaluates exact, prefix, and regex locations according to their precedence rules.
How NGINX chooses the server block
1. The listen address and port come first
NGINX starts with the address and port on which the connection arrived. A request received on one listen socket is not compared with servers bound to a different address or port. This is why checking location blocks first can waste time when a request appears to use the wrong virtual host: confirm the listen address and port before inspecting URI rules.
2. server_name matching priority
After the listen socket is identified, NGINX compares the host name with the server_name declarations associated with that socket. The search proceeds by category and stops at the first matching category. Within wildcard categories, the longest matching wildcard is preferred.
#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.
| Priority | Server-name form | What wins |
|---|---|---|
| 1 | Exact name, such as example.com |
An exact host match |
| 2 | Wildcard beginning with *, such as *.example.com |
The longest matching leading wildcard |
| 3 | Wildcard ending with *, such as mail.* |
The longest matching trailing wildcard |
| 4 | Regular-expression name | The first matching regex in configuration order |
The category order matters. A regular-expression name does not outrank an exact name merely because its pattern looks more specific. Likewise, adding a longer plain wildcard does not move it below or above another category; NGINX completes the higher-priority category before considering the next one.
3. No matching name, an empty host, and the default server
If no server_name matches the request’s Host header, NGINX uses the default server for that listen port. The default is therefore a property of the listen context, not a fallback location inside every 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 →A request without a Host header is assigned an empty server name. You can handle that case explicitly with server_name "". This is distinct from a request whose host is simply unknown: an unknown host follows the default-server rule, while an absent host can match the empty name declaration.
A reliable virtual-host debugging order
- Identify the destination IP address and port used by the client.
- List the
serverblocks attached to that listen address and port. - Check the exact
Hostvalue sent by the client, including its spelling and port if present. - Apply the exact, leading-wildcard, trailing-wildcard, and regex priorities in that order.
- Only after the winning server is known, trace its
locationblocks.
For a controlled test, send an explicit host header to the listener, for example:
curl -i -H 'Host: example.com' http://127.0.0.1/
Testing several host names against the same address makes it easier to distinguish a server-selection problem from a location-selection problem. When reviewing a live configuration, a complete rendered configuration dump (for example, with nginx -T) helps reveal include-file order and the actual order of regex server names.
URI normalization happens before location matching
Location matching does not operate on the raw character sequence copied from a browser’s address bar. NGINX normalizes the URI first. That normalization includes decoding %XX escapes, resolving . and .. path components, and potentially compressing adjacent slashes. The path you need to reason about is therefore the normalized path NGINX uses, not necessarily the original spelling.
Windows 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 reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteQuery-string arguments are separate from the URI used for location matching. A request such as /download/file.zip?token=abc is matched by its path, /download/file.zip; the token argument does not make a different location match. If behavior appears inconsistent, log or otherwise inspect the normalized URI and the selected server rather than relying only on the browser’s display.
The location-selection algorithm
Step 1: exact locations terminate immediately
An exact location has the = modifier, as in location = /health. If the normalized URI exactly matches that value, NGINX stops the location search. No prefix or regex location can override it.
Exact locations are appropriate for one endpoint whose handling must be unambiguous: a root page, a health check, a verification file, or another single URI. Their early termination also avoids unnecessary regex evaluation.
Step 2: NGINX remembers the longest prefix
When no exact location matches, NGINX scans prefix locations such as /, /images/, and /images/icons/. It remembers the longest prefix that matches the beginning of the normalized URI. A plain prefix is not necessarily the final winner; it is a candidate retained while NGINX decides whether regex processing applies.
Step 3: ^~ protects the longest prefix from regex locations
If the longest matching prefix is marked ^~, NGINX uses that prefix immediately and does not test regular-expression locations. This modifier is the explicit way to say that a path family must remain under its prefix handler even when a regex elsewhere would also match.
For example, location ^~ /assets/ protects every normalized URI beginning with /assets/ from a later PHP or image regex. The protection applies because this is the longest matching prefix, not merely because the block appears earlier in the file.
Step 4: regex locations are tested in file order
Without ^~, NGINX tests regex locations after finding the longest prefix. The first matching regex wins. The ~ modifier performs a case-sensitive match; ~* performs a case-insensitive match. Reordering regex blocks can therefore change routing even when none of the patterns changes.
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
A plain, longer prefix does not automatically beat a regex. A regex can override the remembered plain prefix. The practical precedence is therefore: exact match first; then longest prefix selection; then, unless ^~ blocks the process, first matching regex; finally the remembered prefix if no regex matches.
Step 5: fall back to the remembered prefix
If no regex matches, NGINX uses the longest prefix it remembered. This is the normal outcome for paths that belong to a directory-like route but do not satisfy any special file-pattern regex.
Worked configuration
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;
}
}
The configuration contains one exact location, one protected prefix, one ordinary prefix, and one case-insensitive regex. Their outcomes illustrate the entire algorithm:
| Request URI | Selected location | Reason |
|---|---|---|
/ |
location = / |
The exact match terminates the search immediately. |
/assets/logo.php |
location ^~ /assets/ |
The protected longest prefix wins; the PHP regex is skipped. |
/shop/item.php |
location ~* .php$ |
/ is the remembered prefix, then the case-insensitive PHP regex matches first. |
/shop/item.css |
location / |
No regex matches, so the remembered prefix is used. |
The second row is the common surprise: a file name ending in .php does not reach the PHP handler because the matching ^~ prefix deliberately suppresses regex evaluation.
Choosing the right location form
| Form | Best use | Precedence behavior | Case behavior | Maintenance and performance |
|---|---|---|---|---|
location = /path |
One exact URI | Stops all further location checks | Literal exact match | Simple and fastest to reason about |
location /path/ |
A path family | Can be overridden by a matching regex | Literal prefix comparison | Readable and easy to maintain |
location ^~ /path/ |
A path family that must avoid regex interception | Longest matching prefix wins without regex testing | Literal prefix comparison | Provides an early decision and protects intent |
location ~ pattern |
Case-sensitive patterns | First matching regex in file order | Case-sensitive | Powerful but order-dependent |
location ~* pattern |
Case-insensitive patterns | First matching regex in file order | Case-insensitive | Useful for extensions when case should not matter; still order-dependent |
Prefer an exact location when the requirement concerns one URI, a plain prefix when a straightforward path family is sufficient, and ^~ when regex interception would be undesirable. Use regex only when the routing rule genuinely depends on a pattern that prefixes cannot express. Keep related regexes in an intentional order and document broad patterns that could capture requests meant for narrower ones.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Common causes of an apparently wrong match
The request reached another server
The most consequential error is debugging a location in a server that never won host selection. Check the listen socket, host header, exact names, wildcard category, regex order, and default server before changing locations.
A regex captured a plain prefix
Seeing a longer prefix in the file does not prove it wins. If that prefix is not exact and not marked ^~, a matching regex can take over. Add ^~ only when the prefix should categorically exclude regex handling; otherwise, place and narrow regexes deliberately.
Regex order changed the result
Two regex locations can both match the same URI, but only the first matching one in configuration order is selected. Includes and generated configuration can make that order less obvious, so inspect the assembled configuration rather than one fragment.
The URI was not the string you expected
Percent escapes, dot segments, adjacent slashes, and case can alter what a location comparison sees. Compare the normalized URI with the pattern. Remember that query arguments are not part of the location URI.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Case sensitivity was intentional but overlooked
~ and ~* are different decisions. A case-sensitive extension rule will not match a differently cased spelling, while a case-insensitive rule may capture more requests than expected. Choose the modifier to match the policy you actually need.
A practical test matrix
Before deploying a routing change, test one request for each decision boundary. The following matrix can be adapted to your own names and paths:
- An exact URI that should terminate immediately.
- A URI under a protected
^~prefix that also satisfies a regex. - A URI under an ordinary prefix that satisfies a regex.
- A URI under an ordinary prefix that satisfies no regex.
- A host that exactly matches a server name.
- A host that matches a wildcard but not an exact name.
- An unknown host that should reach the configured default server.
- A request without a host header if you intentionally handle
server_name "". - Paths containing encoded characters, dot segments, or repeated slashes when normalization affects your policy.
For each test, record the address and port, sent host header, normalized path, selected server, and selected location. That record separates a server-name failure from a location-precedence failure and exposes regex-order changes during configuration reviews.
Official wording behind the algorithm
NGINX’s core-module documentation states: “To find location matching a given request, nginx first checks locations defined using the prefix strings (prefix locations).” Its server-names documentation describes a search that “is performed in the following order of priority and terminates on the first matching variant.” Those statements explain the two central rules: prefix candidates are established before regex evaluation, and server-name categories are not searched indefinitely after a higher-priority match is found.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Repair Windows errors before they cause bigger problems3Fix the driver behind crashes, sound loss and screen glitchesQuick Recap
Key rules to retain
- Server selection always precedes location selection.
- The listen address and port constrain which servers can compete.
- Exact server names outrank wildcards, and wildcards outrank regex names.
- An exact
=location ends location searching immediately. - NGINX remembers the longest prefix, but a plain prefix can be overridden by a regex.
^~makes the longest matching prefix win without regex evaluation.- Regex locations are evaluated in file order; reordering them can change the result.
- Matching uses a normalized URI, while query-string arguments are separate.
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.




