Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

How to Write Nginx Rules for Wildcard URLs: Hostnames, Paths, Redirects, and Captures

A practical guide to Nginx wildcard rules: distinguish hostnames from URI paths, use server_name, location, rewrite, and map correctly, and avoid precedence, capture, and rewrite-loop mistakes.
Length11 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Start by deciding what the wildcard describes. Use server_name when the changing part is a hostname such as tenant.example.org; use location when it is a URI path such as /downloads/; use rewrite when a matched URI must change or redirect; and use map when you need to turn host or path classification into a variable reused elsewhere. Hostname wildcards and path matches follow different syntax and precedence rules, so putting a path pattern in server_name will never match the URL path.

Choose the directive that matches the part of the request that varies

An HTTP request has separate pieces: the host in the Host header, the URI path, and the action Nginx should take after matching. A reliable configuration begins by isolating that decision instead of trying to make one wildcard expression do everything.

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.
Reader’s requirement Directive What it selects or changes Typical pattern
Route every subdomain server_name Selects a virtual server from the hostname *.example.org
Route a family of paths location Selects processing rules from the normalized URI location /downloads/
Change a matched URI rewrite Replaces the URI internally or sends a redirect rewrite ^/old/(.*)$ /new/$1 permanent;
Reuse a host or path classification map Computes a variable when that variable is used map $host $site_root { ... }

These directives can be combined. A server_name can select a tenant, a location can select the application endpoint, and a rewrite can normalize an old path before proxying. The matching stages are still independent, so each pattern must be valid for the value it examines.

Match wildcard hostnames with server_name

Basic subdomain wildcard

For a site that should answer every first-level subdomain, put the wildcard in the server block:

server {
    listen 80;
    server_name *.example.org;
    root /srv/www/example;
}

This pattern matches names such as shop.example.org and docs.example.org. It is a hostname rule; it does not inspect the path after the hostname. A request for shop.example.org/downloads/file.zip reaches this server because of the host, and a separate location decides what happens to /downloads/file.zip.

Wildcard placement is restricted

Nginx permits an asterisk only at the beginning or the end of a name component on a dot boundary. The common prefix wildcard *.example.org is valid. A suffix form such as mail.* follows the same boundary principle. A pattern such as www.*.example.org is invalid because the asterisk is in the middle of a name.

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

If the variable label really is in the middle, use a regular-expression server name instead:

server {
    listen 80;
    server_name ~^www.(?<section>[a-z0-9-]+).example.org$;

    root /srv/www/$section;
}

The leading ~ marks a regular-expression server name. The ^ and $ anchors require the complete hostname to fit the expression, and each literal dot is escaped. The named section capture becomes an Nginx variable that can be used later in the server block.

Include the bare domain when needed

*.example.org describes subdomains. If the apex name and its subdomains should use the same server, the special .example.org form matches both example.org and names below it:

server {
    listen 80;
    server_name .example.org;
    root /srv/www/example;
}

Choose this form deliberately. If the apex domain needs different content, give it an exact server_name example.org in its own server block instead.

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

Understand hostname precedence

When more than one server name could match, exact names take priority over wildcard names. Among wildcard names, the longest matching wildcard wins. Regular-expression server names are considered according to Nginx’s server-name selection rules, so avoid overlapping expressions that make the result difficult to predict. A practical arrangement is to define exact exceptions first, use one clear wildcard for the general case, and reserve regex names for structures that ordinary wildcard syntax cannot express.

Match wildcard paths with location

Use a prefix location for a path family

A prefix location is the simplest way to match every normalized URI beginning with a path:

server {
    listen 80;
    server_name example.org;

    location /downloads/ {
        proxy_pass http://downloads_backend;
    }
}

This location covers /downloads/, /downloads/file.zip, and deeper descendants. It does not mean “any host containing downloads”; it operates only after a server has been selected from the hostname.

Add the ^~ modifier when this prefix must keep regular-expression locations from taking over:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
location ^~ /downloads/ {
    proxy_pass http://downloads_backend;
}

The modifier still performs a prefix match, but it tells Nginx not to test regex locations after this prefix has won the initial comparison.

Use a regular expression when the path shape matters

Regex locations are appropriate when a path must contain a particular structure or when part of it must be captured:

location ~ ^/docs/(.*)$ {
    proxy_pass http://docs_backend;
}

~ makes the expression case-sensitive. Use ~* for case-insensitive matching when that behavior is genuinely required. The capture in this example is available to later directives as $1.

Anchor expressions that are intended to describe a whole path. Without ^ and $, an expression can match a substring of an unintended URI. Escape literal dots in regexes; an unescaped dot means “any character,” not a period.

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

Location precedence is not simply “regex wins”

Nginx first evaluates prefix locations and remembers the longest matching prefix. It then checks regular-expression locations in the order they appear in the configuration. The first matching regex is selected unless the remembered prefix used ^~.

Configuration situation Result
No prefix matches Nginx checks regex locations in file order and uses the first match.
Several prefixes match The longest prefix is remembered.
Longest prefix has no ^~ Regex locations are checked; the first matching regex can replace the remembered prefix.
Longest prefix uses ^~ Regex locations are skipped and the longest prefix handles the request.

This order explains why placing a broad regex near the top of a file can unexpectedly intercept a more specific path. Put related regex locations in an intentional order and use ^~ for prefixes that must be authoritative.

Redirect or internally rewrite a wildcard path

Rewrite syntax

The directive has the form rewrite regex replacement [flag];. For example, redirect every URI beginning with /old/ to the corresponding /new/ path:

server {
    listen 80;
    server_name example.org;

    rewrite ^/old/(.*)$ /new/$1 permanent;
}

The expression captures everything after /old/. The permanent flag causes Nginx to return a permanent redirect, so the client requests the replacement URI. Test this kind of change with a client that shows response headers before relying on browser caching.

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

Choose last or break for an internal change

An internal rewrite changes request processing without sending a redirect. Use last when Nginx should start a new location search using the rewritten URI:

location /legacy/ {
    rewrite ^/legacy/(.*)$ /current/$1 last;
}

location /current/ {
    proxy_pass http://current_backend;
}

Use break when processing should continue in the current location after the URI changes:

location /files/ {
    rewrite ^/files/(.*)$ /storage/$1 break;
    proxy_pass http://storage_backend;
}

Rewrite directives run sequentially in their configured order. A later expression sees the URI produced by an earlier one, so order matters when several transformations apply.

Avoid rewrite loops

A rewrite that produces a URI matching its own condition can repeatedly trigger internal redirects. For example, rewriting /old/x to another URI that still satisfies ^/old/ creates a cycle. Make the replacement leave the matching namespace, add a clear exclusion, or replace the rewrite with a direct location rule. When a loop occurs, inspect the Nginx error log and the active configuration rather than adding another rewrite blindly.

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

Use named captures instead of fragile positional captures

Positional variables such as $1 are convenient for one expression, but they represent the captures from the most recently evaluated regular expression. If another regex runs before the variable is consumed, the value can be replaced.

Named captures make the dependency explicit:

server {
    listen 80;
    server_name ~^(?<tenant>[a-z0-9-]+).example.org$;

    location ~ ^/assets/(?<asset_path>.*)$ {
        root /srv/sites/$tenant;
        try_files /assets/$asset_path =404;
    }
}

Here $tenant comes from the server-name regex and $asset_path comes from the location regex. Naming captures is especially helpful when several regex directives, nested locations, or rewrites are involved. Keep capture names unique and document which directive creates each variable.

Use map when classification is reused

A map belongs in the http context. It defines a variable from strings or regular expressions, and Nginx evaluates the mapping when the resulting variable is used:

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;
    }
}

This separates host classification from the server’s content rules. A request whose host fits the regex receives a root containing the named tenant; all other hosts use the default path. The regex entry can use named or positional captures, but named captures are easier to audit when the map grows.

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

When a map is preferable

  • Several locations need the same tenant, language, or host classification.
  • You want one default value for hosts that do not match a known pattern.
  • The classification should be defined once rather than copied into multiple rewrites.
  • You need to select a variable such as a root, upstream name, or feature flag without changing the request URI.

Do not use map merely to hide a single simple prefix match. A direct location is easier to read when no reusable classification is needed.

A repeatable procedure for writing a wildcard rule

  1. Write down the changing component. Decide whether the variable text appears before the first slash in the host, inside the URI path, or in the destination of a redirect.
  2. Select the narrowest directive. Start with server_name for hosts, a prefix location for a path family, a regex location for a structural pattern, rewrite for a URI transformation, and map for a value reused by other directives.
  3. Prefer ordinary wildcard or prefix syntax first. Use *.example.org or location /downloads/ when they express the requirement. Move to regex syntax only when the allowed wildcard form cannot describe it.
  4. Anchor and escape regexes. Add ^ and $ when the entire host or path is the subject, and escape literal dots.
  5. Name captures that cross directive boundaries. A named capture communicates its purpose and avoids accidental replacement of $1 by another regex.
  6. Check precedence. For paths, identify the longest prefix, inspect regex locations in file order, and decide whether ^~ is required. For hosts, check exact names and overlapping wildcards.
  7. Choose rewrite behavior explicitly. Use a redirect flag when the client must see a new URL; use last to perform a fresh location search; use break to remain in the current location.
  8. Validate before reload. Run nginx -t against the configuration that will be loaded. If the service uses a non-default file, validate that file or the corresponding include tree.
  9. Inspect the effective configuration. nginx -T prints the complete loaded configuration, which helps reveal an included server block or regex location that changes precedence.
  10. Test each branch. Send requests for an exact host, a matching wildcard host, a nonmatching host, the shortest matching path, a deeper path, and a near miss that should not match.

Testing examples and expected observations

For a local test, direct the hostname to the intended address while preserving the Host header:

curl --resolve shop.example.org:80:127.0.0.1 http://shop.example.org/downloads/file.zip

To inspect a redirect without following it, request headers only:

curl -I --resolve example.org:80:127.0.0.1 http://example.org/old/manual.pdf

A successful permanent redirect should return a redirect status and a Location header containing the replacement URI. An internal rewrite should not expose a changed URL to the client; the response should come from the location selected after the internal processing. Test a nonmatching hostname as well, because a default server can answer requests that do not fit the intended wildcard.

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.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common mistakes and precise fixes

Putting a path wildcard in server_name

server_name example.org/downloads/* cannot match a URI path. Keep server_name example.org for the host and put location /downloads/ in that server block.

Using an illegal middle asterisk

www.*.example.org is not a valid ordinary wildcard server name. Replace it with a carefully anchored regex server name and escape its dots.

Leaving regexes unanchored

An expression such as docs can match a substring in a host or path that was not intended. Add boundaries and define the allowed characters explicitly.

Forgetting regex location order

A regex location is not automatically stronger than every prefix. Re-evaluate the longest prefix and the order of regex locations; add ^~ if a prefix must win.

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

Reusing $1 too late

Another regex can overwrite positional captures. Consume the value immediately or use a named capture whose purpose is clear.

Reloading the wrong configuration

A valid edit has no effect if Nginx is loading a different file or an included server block overrides it. Validate and print the active configuration, then reload the service using the deployment method for your system.

Creating an accidental redirect or rewrite cycle

Check that each replacement no longer satisfies the original condition. If the error log reports repeated internal redirects, simplify the rule and separate old and new URI namespaces.

Operational and security considerations

  • Constrain tenant labels. A regex such as [a-z0-9-]+ limits which host labels can become directory names. Do not pass arbitrary host text into a filesystem path.
  • Provide a safe default. A map default or an explicit default server prevents unknown hosts from selecting an unintended tenant.
  • Keep path and host rules separate. This makes audits easier and reduces the chance that a new regex changes unrelated traffic.
  • Use the narrowest match. Broad regexes are harder to reason about and may intercept requests intended for a more specific location.
  • Plan redirect permanence. A permanent redirect can be cached by clients and intermediaries. Confirm the destination and test in a controlled environment before deploying it broadly.
  • Log enough context while troubleshooting. Include the host and request URI in temporary diagnostic logging so you can tell which branch received a request; remove noisy diagnostics after the rule is verified.

Reference configurations

Subdomains plus a protected download prefix

server {
    listen 80;
    server_name *.example.org;

    location ^~ /downloads/ {
        proxy_pass http://downloads_backend;
    }

    location / {
        proxy_pass http://web_backend;
    }
}

The wildcard selects any matching subdomain. The ^~ prefix ensures that a later regex location cannot unexpectedly take over downloads, while the general prefix handles everything else.

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.

Tenant host, path capture, and internal routing

server {
    listen 80;
    server_name ~^(?<tenant>[a-z0-9-]+).example.org$;

    location ~ ^/v1/(?<resource>[a-z0-9/_-]+)$ {
        proxy_set_header X-Tenant $tenant;
        proxy_set_header X-Resource $resource;
        proxy_pass http://api_backend;
    }

    location / {
        root /srv/sites/$tenant;
    }
}

The host regex creates $tenant; the URI regex creates $resource. Restricting both captures to expected characters avoids treating arbitrary request text as routing metadata.

Deployment checklist

  • Is the wildcard matching a hostname or a URI path?
  • Is the chosen directive limited to that component?
  • Are ordinary wildcard and prefix forms sufficient?
  • If a regex is necessary, are the anchors present and literal dots escaped?
  • Are wildcard server-name boundaries legal, with no middle asterisk?
  • Have exact names, overlapping wildcards, longest prefixes, and regex file order been checked?
  • Should a prefix use ^~?
  • Are captures named when more than one regex can run?
  • Does the rewrite need a client-visible redirect, a new location search with last, or current-location processing with break?
  • Does the replacement avoid matching the same rewrite again?
  • Have nginx -t and nginx -T been run against the active configuration?
  • Have matching, nonmatching, shortest-path, deep-path, and redirect cases been tested?

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 quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
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.