Recommended Free Tools
iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
Need a server to try this on? Antihost offers Linux VPS plans with NVMe storage, full root access and a 14-day free trial.
The correct Nginx wildcard rule depends on what changes. Use server_name when the wildcard is in the hostname, location when it is in the URL path, rewrite when a matching path must change or redirect, and map when you want to turn host or path classification into a variable reused elsewhere. These directives are not interchangeable: a wildcard in server_name never matches a path, and a regex location does not automatically override every prefix location.
Choose the directive by what varies
Start by identifying the part of the request that contains the pattern. The host is the domain and subdomain sent before the path; the URI path begins after the host. Nginx applies different matching rules to each.
| Need | Directive | What it does | Typical pattern |
|---|---|---|---|
| Match subdomains or other hostnames | server_name |
Selects a virtual server from the request host. | *.example.org |
| Match a family of paths | location |
Selects request handling for a URI prefix or regular expression. | location /downloads/ |
| Change a matching URI | rewrite |
Redirects the client or internally changes the URI. | rewrite ^/old/(.*)$ /new/$1 permanent; |
| Classify a host or URI for reuse | map |
Creates a variable from strings or regular expressions. | map $host $site_root { ... } |
A useful rule of thumb is “selection first, transformation second.” server_name and location select configuration; rewrite transforms the URI; map computes a value that other directives can consume.
Compare the approaches before writing a rule
When several directives appear possible, compare five properties. First, identify what is matched: a hostname, a path prefix, or a path expression. Second, decide whether the URI should change for the client or only for Nginx internally. Third, check precedence: server-name selection has its own exact and wildcard ordering, while location matching uses longest-prefix selection followed by regular-expression checks. Fourth, decide whether a captured value must be reused. Finally, decide whether the rule belongs in one server or location block or should be centralized as a reusable map variable. This short analysis prevents the common mistake of putting a path pattern in a hostname directive or using a rewrite when simple location selection would be clearer.
#1 Best Overall
Match every subdomain with server_name
Simple wildcard hostname
For ordinary subdomains, put the wildcard in the server_name directive:
server {
listen 80;
server_name *.example.org;
root /srv/www/example;
}
This pattern matches names such as shop.example.org and api.example.org. It is a hostname rule; it says nothing about whether the request path is /, /downloads/, or another URI. Every path arriving on a matching host still goes through the locations inside the selected server block.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Wildcard placement rules
Nginx allows an asterisk only at the beginning or end of a name, and only on a dot boundary. *.example.org is valid. A pattern such as www.*.example.org is invalid because the asterisk is in the middle of a name label. Use a regular-expression server name when the variable part is not at an allowed boundary.
A special leading-dot form, .example.org, matches both the bare domain example.org and its subdomains. This is different from *.example.org, which is the wildcard form for subdomains. Choose the leading-dot form when one server must answer for both the apex name and all subordinate names.
Which server block wins
Nginx gives exact names priority over wildcard names. If several wildcard names match, the longest matching wildcard is selected. This lets you keep a broad default and add a more specific host rule without relying on file order. A carefully chosen exact name can therefore override a broad wildcard for one special host.
Regex hostname with a named capture
Use a regex server name when you need a controlled pattern or want to extract the changing label:
server {
listen 80;
server_name ~^(?<tenant>[a-z0-9-]+).example.org$;
location / {
root /srv/sites/$tenant;
}
}
The leading ~ marks a regular-expression server name. The ^ and $ anchors require the complete hostname to match, while . treats each dot as a literal dot rather than a regular-expression wildcard. The character class limits the changing label to lowercase letters, digits, and hyphens. The named capture tenant becomes an Nginx variable that can be used by later directives.
Use a named capture when the value must survive several configuration operations. Positional captures such as $1 are convenient, but another regex evaluation can replace them during the same request. A named variable makes the intended value explicit and avoids depending on the order of unnamed groups.
Match wildcard URL paths with location
Prefix location for every path below a directory
For a path family, use a prefix location:
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/manual.pdf and /downloads/2026/archive.zip. The slash is part of the prefix, so it does not also match a path such as /downloaded/. Prefix syntax is usually the clearest and least fragile choice when the varying part is simply everything below one directory-like path.
Regular-expression location with a capture
Choose a regex location when the path needs a pattern more precise than a simple prefix:
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 →location ~ ^/docs/(.*)$ {
proxy_pass http://docs_backend;
}
The ~ modifier makes the regex case-sensitive. Use ~* for case-insensitive matching. The capture $1 contains the part matched by (.*); named captures are preferable when multiple regex directives may run. Anchoring the expression means the location describes the intended path shape rather than a substring found somewhere inside a longer URI.
Rank #2
Location precedence is not “regex always wins”
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. If a regex location matches, it is normally used; however, adding ^~ to the selected prefix prevents regex locations from being checked:
location ^~ /downloads/ {
proxy_pass http://downloads_backend;
}
location ~ .php$ {
proxy_pass http://php_backend;
}
With this arrangement, a request under /downloads/ stays with the downloads prefix even if its path also matches the PHP regex. Without ^~, the regex phase can take over after the longest prefix has been found. Put regex locations in a deliberate order because the first matching regex is used. When debugging an unexpected handler, write down the longest prefix first, check for ^~, and then review each regex in file order.
Prefix or regex: a practical choice
Use a prefix when all descendants should be treated alike and readability matters. Use a regular expression for a constrained suffix, a file-name shape, or a path that cannot be expressed as one continuous prefix. Do not add a regex merely to make a prefix look “wildcard-like”; location /downloads/ already covers every normalized URI below that prefix.
Free tools Windows power users keep installed
One-click scans. No signup required.
Redirect or internally route a wildcard path with rewrite
Permanent redirect
The rewrite syntax is:
rewrite regex replacement [flag];
To send clients from an old path family to a new one, anchor the old path and preserve the captured suffix:
server {
listen 80;
server_name example.org;
rewrite ^/old/(.*)$ /new/$1 permanent;
}
A request for /old/guide.html is redirected to /new/guide.html. The permanent flag returns a permanent redirect, so test the rule before deploying it broadly. Anchoring with ^ and $ prevents an accidental substring match. Preserving the suffix with a capture keeps each old resource mapped to its corresponding new resource instead of sending every request to one fixed destination.
Internal routing with last or break
Not every rewrite should reach the browser. For an internal route change, choose the flag according to how Nginx should continue:
last: rewrite the URI and start a new location search. Use this when the new URI should be handled by a differentlocation.break: stop processing rewrite directives for the current level and continue in the current location.
Rewrite directives run sequentially in their configured order. A later regex can therefore see a URI changed by an earlier rule, and a positional capture can be replaced. Keep related rewrites ordered and use named captures when values must be carried forward. Choose last only when a second location lookup is intended; otherwise, break keeps processing at the current level.
Avoid rewrite loops
A loop occurs when a rewrite produces a URI that matches the same rewrite again, directly or after an internal location search. Design the destination so it no longer satisfies the source pattern, and inspect Nginx’s error log if requests repeatedly undergo internal redirects or never reach the intended handler. Test the destination itself, not just the source request, because a destination that appears correct in a single hop can still trigger another rule.
Use map for reusable wildcard classification
Use map when the same host or URI decision should feed several directives, or when the result is a variable such as a tenant-specific document root:
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;
}
}
The map creates $site_root from the request host. A matching regex can contain named or positional captures. Nginx evaluates the mapping when the result variable is used, which avoids doing the classification for requests that never consume it. Keep the map in the http context and reference the resulting variable in servers, locations, or other directives that accept variables.
The default entry gives unmatched hosts a defined result. The regular-expression entry then supplies a tenant-specific path for names that fit the anchored pattern. Prefer map over duplicating the same regex in multiple locations. The matching rule remains in one place, while each consumer simply uses the computed variable. Centralizing the expression also reduces the chance that two server blocks drift apart and classify the same host differently.
Rank #3
Capture values safely
Named versus positional captures
| Capture style | Example | Strength | Risk |
|---|---|---|---|
| Named | (?<tenant>...) then $tenant |
Readable and easier to carry into later directives. | The name must be unique and correctly referenced. |
| Positional | (...) then $1 |
Short for a single simple regex. | Another regex match can overwrite the numbered capture. |
Use a named capture for tenant names, path segments, or any value used outside the immediately following replacement. If you use $1, consume it before another regex directive can run and verify that the grouping order has not changed. Adding a new parenthesized group to an expression can shift every later number, while a named capture keeps references tied to the value’s purpose.
Anchor and escape every regex intentionally
- Use
^at the beginning when the match must start at the beginning of the host or path. - Use
$at the end when trailing text must not be accepted. - Escape literal dots as
.; an unescaped dot means “any character” in a regular expression. - Use a character class such as
[a-z0-9-]+when the variable label has a defined alphabet instead of accepting arbitrary text.
Anchors are especially important for host regexes. Without them, a valid-looking tenant expression might also match a longer, unintended host containing the same text. Escaping dots makes the boundary explicit and prevents the expression from accepting another character in place of the dot.
Complete decision examples
Every tenant subdomain, same path handling
If all tenant subdomains share one application, use a wildcard hostname and a normal root location:
server {
listen 80;
server_name *.example.org;
location / {
proxy_pass http://app_backend;
}
}
This is the simplest host-selection case: the wildcard is only in server_name, while the path is handled uniformly.
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 reinstallOutdated 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 matchOne host, a special downloads path
If only the path varies, keep the host exact and add a path prefix:
server {
listen 80;
server_name example.org;
location ^~ /downloads/ {
proxy_pass http://downloads_backend;
}
location / {
proxy_pass http://app_backend;
}
}
The ^~ modifier reserves the downloads subtree from regex locations defined elsewhere in the server.
Old wildcard path to a new wildcard path
When the browser should show the new URL, use a redirect and preserve the suffix:
rewrite ^/legacy/(.*)$ /current/$1 permanent;
When the browser should keep the original URL and only Nginx’s internal handler should change, use the same anchored pattern with last and provide a destination location that cannot trigger the source rule again.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsTenant-specific roots with a reusable map
When many directives need the same tenant classification, put the regex in map, expose a variable such as $site_root, and use that variable wherever the selected filesystem root is required. This avoids repeating a potentially divergent regex in each server or location block.
Combining host and path decisions
A request can require both kinds of matching. First select the server by exact, wildcard, or regex hostname. Then let locations select the path inside that server. If the path must be renamed, apply a rewrite with an intentional flag. If the host classification feeds several later choices, compute it once with map and consume the resulting variable. Keeping these stages separate makes it clear whether a failure came from host selection, location precedence, or URI transformation.
Validate a wildcard rule before rollout
- Write down whether the changing text is in the host, path, or both. Select
server_name,location,rewrite, ormapaccordingly. - Check wildcard placement. A hostname asterisk belongs only at the first or last name part on a dot boundary; use a regex server name for a middle label.
- Anchor regexes and escape literal dots. Confirm that the allowed character class matches the names or paths you intend to serve.
- Review location precedence. Find the longest prefix, note whether it has
^~, and then inspect regex locations in file order. - Review captures. Replace fragile
$1references with named captures when more than one regex can run. - Check rewrite flow. Use
permanentonly for a client-visible redirect; uselastfor a new location search orbreakto remain in the current location. - Run the configuration test command, inspect the fully expanded active configuration, reload only after it parses successfully, and exercise both matching and non-matching requests.
- For redirects, test with a client that displays response headers and confirm the
Locationtarget, status, and number of hops. Test a destination URL as well as the source URL to catch loops.
Include boundary cases in the test set: an exact hostname that should override a wildcard, a host that should fall through to the default map value, a path just inside and just outside a prefix, and a URI that matches more than one regex location. These cases reveal precedence mistakes that a single happy-path request will not show.
Rank #4
Common mistakes and fixes
Putting a path wildcard in server_name
server_name example.org/downloads/* does not match a URI path. server_name examines the host only. Move the path pattern into location or rewrite.
Using an invalid middle wildcard
www.*.example.org is not a valid wildcard server name. Replace it with a regex server name such as ~^www.(?<tenant>[a-z0-9-]+).example.org$, with anchors and escaped dots.
Expecting a regex location to override everything
A longest prefix is selected first, and a ^~ prefix suppresses regex checks. Remove or adjust ^~ when a regex must be considered, or move the special handling into the prefix location that actually owns the path.
Allowing a partial regex match
Without anchors, a regex can match a substring inside a larger host or path. Add ^ and $ when the whole intended value must conform.
Reusing an overwritten positional capture
If a later regex runs before $1 is consumed, the value may no longer be the segment you expected. Use a named capture or restructure the directives so the value is used immediately.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Creating an internal redirect cycle
Check whether the rewritten URI still matches the source rule or another rule that points back to it. Make the source and destination patterns distinct, then use the error log to identify repeated internal redirects.
Duplicating one classification in many places
Copying a tenant or path regex into several locations invites subtle differences in anchors, character classes, or replacement values. Put the shared decision in an http-level map and let each consumer use the resulting variable.
Frequently asked questions
How do I match every subdomain with Nginx?
Use server_name *.example.org; for subdomains. Use .example.org when the same server must also match the bare domain. If the variable label needs validation or extraction, use an anchored regex server name with a named capture.
How do I write a wildcard location for URLs?
Use a prefix such as location /downloads/ { ... } for every normalized URI below that path. Use location ~ ^/docs/(.*)$ { ... } when the path requires a regular expression, and choose ~* when matching should ignore case.
Crashes, 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 minuteWindows 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 reinstallHow do I redirect all URLs that start with a pattern?
Use an anchored rewrite, for example rewrite ^/old/(.*)$ /new/$1 permanent;. The capture preserves the suffix. Use permanent only when the browser should receive a redirect; use last or break for internal processing.
Should I use server_name, location, rewrite, or map?
Use server_name for hostnames, location for selecting path handling, rewrite for changing a URI, and map for computing a reusable variable from a host or URI classification.
Best Value
Why is my regex location not being used?
Nginx first finds the longest prefix. If that prefix has ^~, regular-expression locations are not checked. Otherwise, regex locations are tested in configuration order, and the first matching regex is selected.
Why does my wildcard hostname not match?
Check that the asterisk is only at the beginning or end of a name on a dot boundary. A middle wildcard such as www.*.example.org is invalid. Use a regex server name with anchors and escaped dots for that shape.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsWhen should I use a named capture instead of $1?
Use a named capture whenever more than one regex directive can run or the value is used beyond one immediate replacement. Positional captures can be overwritten by a later regex, while a named variable documents which value you intend to carry forward.
How can I check for a rewrite loop?
Test both the source and destination URLs, inspect redirect headers and hop count, and review the error log for repeated internal redirects. Ensure the rewritten destination no longer satisfies the source rule or another rule that points back to it.
Practical checklist
- Hostname wildcard:
server_name *.example.org;or the special combined form.example.org. - Path prefix:
location /downloads/ { ... }; add^~when regex locations must not take over. - Path regex: start with
~or~*, anchor the expression, and escape literal dots. - URI redirect: use
rewrite regex replacement permanent;only when the client should receive a permanent redirect. - Internal route change: choose
lastfor a new location search orbreakto continue in the current location. - Reusable classification: put the host or URI regex in an
http-levelmapand consume its variable. - Captures: prefer named variables when more than one regex directive is involved.
- Operations: test the active configuration, inspect redirect headers, and verify both matching and non-matching cases before production.
Frequently Asked Questions
What is the simplest rule for all subdomains?
Use server_name *.example.org;. Use .example.org instead when the bare domain and its subdomains should share the server.
Can server_name match a URL path?
No. server_name matches the request host. Put path patterns in location or rewrite.
How do I stop a regex location from taking over a prefix?
Add ^~ to the longest prefix, such as location ^~ /downloads/. Nginx then skips regex locations for that request.
What do last and break mean in a rewrite?
last rewrites the URI and starts a new location search. break stops rewrite processing at the current level and continues in the current location.
Why should regexes use anchors and escaped dots?
^ and $ require the complete intended host or path to match. . matches a literal dot; an unescaped dot matches any character.
When is map better than repeating a regex?
Use map when one host or URI classification feeds multiple directives. It computes a reusable variable from strings or regexes and keeps the rule in one place.
The Bottom Line
Write the wildcard where the variation actually occurs: server_name for hosts, location for paths, rewrite for URI changes, and map for reusable classification. Respect wildcard placement and location precedence, anchor and escape regular expressions, prefer named captures when values cross regex directives, and test both redirects and non-matching requests before rollout.
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.

