The right NGINX directive depends on the part of the request that varies: use server_name for wildcard hostnames, location for URI paths, rewrite when the URI must change or redirect, and map when you want to turn a host or path classification into a reusable variable. A hostname wildcard such as *.example.org is not interchangeable with a path rule such as location /downloads/. The examples below show the matching rules, precedence, captures, redirects, testing procedure, and failure modes that matter in production.
Need a server to try this on? Antihost offers Linux VPS plans with NVMe storage, full root access and a 14-day free trial.
Choose the directive by what changes
Every HTTP request has at least two values that people commonly call a “URL”: the host name and the URI path. NGINX evaluates them in different parts of its configuration. Decide which value contains the wildcard before writing a rule.
As an Amazon Associate I earn from qualifying purchases.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →| Reader need | Directive | What it matches or produces | Typical use |
|---|---|---|---|
| Match any subdomain | server_name |
Host name in the HTTP request | *.example.org |
| Match a path prefix | location with a prefix |
Normalized URI beginning with a string | location /downloads/ |
| Match a path or host with a pattern | location ~ or regex server_name |
Regular expression, optionally with captures | ^/docs/(.*)$ |
| Change or redirect a URI | rewrite |
Replaces a matching URI and applies a flag | /old/... to /new/... |
| Reuse a classification | map |
Creates a variable from a string or regular expression | Map a tenant host to a document root |
A server_name rule chooses the virtual server; a location rule chooses request handling inside that server. Neither one redirects a client by itself. A redirect requires a response-producing directive such as rewrite ... permanent or an explicit redirect return.
Match wildcard hostnames with server_name
Basic subdomain wildcard
Put the wildcard in the server block when the variable part is the host name:
#1 Best Overall
server {
listen 80;
server_name *.example.org;
root /srv/www/example;
}
This accepts host names such as blog.example.org and api.example.org. It does not make a path wildcard; https://example.org/downloads/file.zip still has the host example.org and the path /downloads/file.zip.
Include the apex domain when required
The special form .example.org matches both the bare name example.org and names below it, including blog.example.org. Use it when one server should handle the apex and all subdomains:
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteserver {
listen 80;
server_name .example.org;
root /srv/www/example;
}
A leading-dot name is different from writing only *.example.org, which targets subdomains and does not include the bare domain.
Wildcard placement is restricted
NGINX allows an asterisk only at the beginning or the end of a name, and only on a dot boundary. Therefore *.example.org is valid. A pattern such as www.*.example.org is invalid because the wildcard is in the middle. If the changing part is in the middle, use a regular-expression server name instead.
Server-name precedence
When several server names could match, NGINX gives priority to an exact name over wildcard names. Among wildcard names, the longest matching wildcard is selected. Regex server names are evaluated according to NGINX’s server-name selection rules, so keep overlapping patterns explicit and test the active configuration rather than relying on visual order alone.
Match wildcard paths with location
Prefix locations cover a whole path branch
For a path that starts with a known directory, a prefix location is usually the clearest and fastest rule:
server {
listen 80;
server_name example.org;
location /downloads/ {
proxy_pass http://downloads_backend;
}
}
This matches every normalized URI beginning with /downloads/, including deeper paths such as /downloads/manuals/v2.pdf. It is not a shell glob: do not write /downloads/*. The literal prefix is enough.
Rank #2
Prefix matching and the ^~ modifier
NGINX first considers prefix locations and remembers the longest matching prefix. It then checks regular-expression locations in the order they appear in the configuration. A regular expression can therefore take over a request that appears to fit a prefix. Add ^~ when the longest prefix must prevent regex locations from being checked:
location ^~ /downloads/ {
proxy_pass http://downloads_backend;
}
Without ^~, a later expression such as location ~ .php$ may handle a file under /downloads/ instead. With ^~, NGINX uses the selected prefix and skips regex locations for that request.
Exact locations for one URI
An equals modifier is useful when only one path should receive special handling:
Recommended Free Tools
location = /downloads {
return 301 /downloads/;
}
This exact match is separate from the broader /downloads/ prefix. It is a practical way to normalize a directory URL before requests enter the directory’s handler.
Use regular-expression locations for patterned paths
Case-sensitive and case-insensitive modifiers
The ~ modifier makes a location regular expression case-sensitive. The ~* modifier makes it case-insensitive:
location ~ ^/docs/(.*)$ {
proxy_pass http://docs_backend;
}
location ~* ^/images/(.*).(jpg|png|webp)$ {
expires 7d;
}
Choose case sensitivity deliberately. A case-insensitive image rule may be convenient for extensions, while a case-sensitive application route can avoid treating differently cased paths as the same resource.
Anchor the expression and escape literal dots
Use ^ to anchor the beginning and $ to anchor the end when the entire intended path must match. In a regular expression, a dot means “any character”; escape it as . when you mean a literal period. For example, ^/docs/(.*)$ describes the complete URI beginning with /docs/, while an unanchored expression could match an unintended substring elsewhere in the URI.
Rank #3
Location matching uses the URI path, not the scheme or host. Keep host conditions in server_name and path conditions in location; combining both concerns in one expression usually makes precedence harder to reason about.
Captures in a location
Parenthesized groups capture text for later directives. In the example above, $1 contains everything after /docs/. Captures are request state, so a later regular-expression evaluation can replace positional values. Named captures are safer when several expressions run:
location ~ ^/docs/(?<document>.*)$ {
add_header X-Document $document;
proxy_pass http://docs_backend;
}
Use a descriptive name whenever the captured value crosses directive boundaries or is consumed in multiple places. Keep the expression anchored so the variable contains only the text you intended.
Redirect or internally rewrite a wildcard path
Permanent redirect for a public URL change
The rewrite syntax is rewrite regex replacement [flag]. To send clients and caches from an old path to a new one:
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
server {
listen 80;
server_name example.org;
rewrite ^/old/(.*)$ /new/$1 permanent;
}
A request for /old/guide receives a permanent redirect to /new/guide. The permanent flag produces a permanent redirect response, so use it only after the destination and pattern are stable.
last versus break
For an internal route change, the flag controls what NGINX does next:
last: rewrite the URI and start a new location search. This is appropriate when the new URI should be handled by a differentlocation.break: stop processing rewrite directives in the current context and continue with the current location. Use it when the request should stay in the existing handler.permanent: return a permanent redirect to the client rather than performing an internal hand-off.
Rewrite directives execute sequentially in their configured order. A later rule sees the result of an earlier rule, so order matters when patterns overlap.
Rank #4
Prevent rewrite loops
A loop occurs when a rewrite produces a URI that matches the same rewrite again, or when successive internal redirects keep re-entering the same rules. Design the destination so it no longer satisfies the source pattern, and inspect the error log if NGINX reports repeated rewrite or internal-redirection cycles. A redirect should have a clearly different, testable destination; an internal rewrite should eventually reach a location that stops rewriting.
Free tools Windows power users keep installed
One-click scans. No signup required.
Capture a wildcard hostname with a regex server name
Use a regex server name when the variable host component is not at the beginning or end, or when you need to capture it for a filesystem path:
server {
listen 80;
server_name ~^(?<tenant>[a-z0-9-]+).example.org$;
location / {
root /srv/sites/$tenant;
}
}
The leading ~ marks the server name as a regular expression. The anchors require the entire host to match. The dot before example is escaped because it is literal, and the named capture tenant becomes an NGINX variable. A request for acme.example.org therefore uses /srv/sites/acme.
The character class in this example permits lowercase letters, digits, and hyphens. It intentionally rejects spaces, underscores, uppercase letters, and an empty tenant. Adjust the class to your naming policy, but keep the end anchor so a valid-looking prefix cannot match a longer unintended host.
Use map when classification is reused
map creates a variable from literal strings or regular expressions. The mapping is evaluated when the resulting variable is used, which lets one classification feed several directives without duplicating a regex:
http {
map $host $site_root {
default /srv/sites/default;
~^(?<tenant>[a-z0-9-]+).example.org$ /srv/sites/$tenant;
}
server {
listen 80;
server_name .example.org;
root $site_root;
}
}
Here, hosts that match the tenant expression map to a tenant-specific root; all other hosts use /srv/sites/default. A regex entry may contain named or positional captures. Prefer named captures when the value is consumed in more than one place, and choose a safe default for unmatched hosts rather than leaving the variable ambiguous.
Use a direct server_name or location rule for a one-off decision. Use map when the same host or URI classification controls the root, proxy target, header, cache policy, or another setting in multiple locations.
Best Value
- Upgraded Two Zipper Pockets: Forvencer server books feature two secure zipper pockets for better organization of coins, cash, and receipts, ensuring that everything you collect has a safe and secure place
- Smart Storage & Quick Access: Designed with 8 multi-functional compartments, the right side includes a guest receipt pad, while the left has a money pocket, ticket pocket, and credit card slot. Two small clear pockets store bills, receipts, and other visible items. A stitched pen loop ensures you always have your favorite pen ready
- High-quality & Easy to Clean: Crafted from high-quality PU leather with heavy-duty stitching, this server book is built to last. It resists tears, scratches, and its waterproof surface makes cleaning easy with just a damp cloth or a non-chlorine sanitizer
- Perfect Fit for Your Apron: Measuring 5” x 8”, this compact organizer is slightly smaller than other models, making it ideal for bending or sitting while carrying in your server apron. It holds everything a waitress needs—a place for everything
- What's Included: This server organizer comes with multiple open and zippered pockets to store money, receipts, tips, etc. Clear sleeves are perfect for keeping menus or special lists while serving. Available in a variety of colors, allowing you to express yourself even when in uniform
How NGINX decides which location wins
- NGINX checks exact and prefix-style locations and identifies the longest matching prefix.
- If the longest prefix has the
^~modifier, regex locations are skipped and that prefix handles the request. - Otherwise, NGINX checks regex locations in configuration order and uses the first matching expression.
- If no regex takes precedence, NGINX uses the remembered longest prefix.
This order explains why simply placing a regex below a prefix does not guarantee that the prefix wins, and why moving a regex earlier can change behavior. Make precedence visible with modifiers and narrow expressions instead of depending on accidental file order.
Test a wildcard rule before reloading production
Validate syntax and inspect the active configuration
- Run
nginx -tto check syntax and confirm that referenced files can be opened. - Run
nginx -Twhen you need to see the complete configuration after includes have been expanded. Verify that the intendedserver_name,location, and rewrite are actually loaded. - Reload only after the test succeeds, using the service manager used by your installation, such as
systemctl reload nginx.
Exercise host and path cases
Test at least one positive and one negative request for every rule. For a hostname wildcard, send requests with the intended host header and with a near miss such as an extra label or an invalid character. For a path rule, test the directory itself, a nested file, a similar prefix, a query string, and a path that should fall through. Use curl -I for redirects and curl -v when you need to see the selected response headers.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →curl -I http://example.org/old/guide
curl -v http://example.org/downloads/manual.pdf
curl -v -H 'Host: acme.example.org' http://127.0.0.1/
Confirm the status code, Location header for redirects, upstream or root selection, and absence of unexpected loops. Test with the same protocol and port that clients will use; an HTTP-only server block does not prove that an HTTPS server block has the same rules.
Common mistakes and precise fixes
Putting a path wildcard in server_name
Symptom: a rule intended for /downloads/... never matches. Cause: server_name examines the host, not the URI. Fix: keep the host in server_name and move the path to a location block or a rewrite expression.
Using an invalid middle wildcard
Symptom: NGINX rejects the configuration or the intended host never selects the server. Cause: patterns such as www.*.example.org violate wildcard placement rules. Fix: use a regex server name with anchors and an escaped dot, for example ~^www.(?<tenant>[a-z0-9-]+).example.org$.
Leaving regexes unanchored or dots unescaped
Symptom: unrelated paths or hosts match. Cause: an unanchored expression can match a substring, and an unescaped dot matches any character. Fix: add ^ and $ around the intended whole value and write literal dots as ..
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 matchPC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Assuming regex locations always win
Symptom: a regex handler takes a request that appears to belong to a longer prefix, or the reverse. Cause: NGINX first selects the longest prefix, then checks regex locations in file order unless ^~ suppresses them. Fix: document the desired precedence, add ^~ where necessary, and test overlapping cases.
Reusing $1 after another regex
Symptom: a proxy target, header, or rewritten path contains the wrong captured text. Cause: positional captures are shared request state and can be overwritten by another regular-expression match. Fix: use named captures such as $tenant or $document, and keep related expressions close together.
Creating an internal redirect cycle
Symptom: requests fail after repeated internal redirects, and the error log records a rewrite cycle. Cause: the rewritten URI still matches the source rule or re-enters an equivalent rule. Fix: make the destination distinguishable, select last or break intentionally, and retest both the original and destination paths.
Quick Recap
A practical decision checklist
- Is the changing value the host? Start with
server_name. - Is the changing value the URI path? Start with a prefix
location. - Do you need pattern matching inside the host or path? Use an anchored regex and escape literal dots.
- Must the browser receive a new URL? Use a redirect flag such as
permanent. - Should NGINX route internally to another handler? Choose
lastfor a new location search orbreakto remain in the current location. - Will several directives use the same classification? Put it in
map. - Could a regex compete with a prefix? Check longest-prefix behavior, regex order, and whether
^~is needed. - Are captures reused? Prefer named variables over positional values.
- Before rollout, anchor expressions, inspect the expanded configuration, run
nginx -t, and test redirects and non-matching requests withcurl.
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.




