SSD Nodes Learn Hosting plans →
Guides Matt ConnorBy Matt Connor

nginx server_name Matching and Wildcards

How nginx picks a server block, from exact names down to regex. Build a curl test lab and learn why *.example.* fails and _ is not a catch-all.

How nginx server_name matching works

nginx server_name matching happens in two steps. First, nginx keeps only the server blocks whose listen directive matches the IP address and port the request arrived on. Then it compares the request's Host header with the server_name entries of those blocks, in a fixed order: the exact name, the longest wildcard that starts with an asterisk, the longest wildcard that ends with an asterisk, and finally the first regular expression that matches, in the order it appears in the configuration. If no name matches, the default server for that address and port answers.

That order answers most "why did the wrong site answer" questions. This guide builds a small lab in a fresh Ubuntu 26.04 container. You send Host headers with curl and see which block answers each one. Then it covers the rules that trip people up: where an asterisk may go, what .example.org means, where the default server comes from, and why server_name _ is not a catch-all.

Step one: the address and port pick the candidates

nginx does not compare names across the whole configuration. It first tests the request's IP address and port against the listen directives. Only the blocks that match that address and port take part in the name test. A block with listen 443 ssl never competes for a request that arrived on port 80, however well its name matches.

This explains a common surprise. You add server_name shop.example.org to a block that listens on 127.0.0.1:80. The request arrives on the public address, and another site answers. The name was right. The block was never a candidate, because its listen address did not match the request.

A block with no listen line at all is not exempt. nginx then uses *:80 when it runs as root, and *:8000 otherwise. Each address and port pair also has its own default server, which a later section covers.

The four kinds of name, in the order nginx tries them

Inside one address and port, nginx tries the names in this order. The first match wins and the search stops.

  1. The exact name, such as www.example.org.
  2. The longest wildcard that starts with an asterisk, such as *.example.org. If *.example.org and *.shop.example.org both match, the longer one wins.
  3. The longest wildcard that ends with an asterisk, such as mail.example.*.
  4. The first regular expression that matches, in the order the blocks appear in the configuration. A regex name starts with a tilde, for example ~^www\d+\.example\.org$.

For exact and wildcard names, the rank decides the winner, not the position in the file. The file order matters in two places: which regex is tested first, and which block becomes the default server when no listen line says default_server.

Regular expressions are also the slowest kind of name. The nginx documentation says they are tested one after another, so a long list of regex names costs time on every request that reaches them. Use an exact name or a wildcard when one can do the job.

Build a test lab in a fresh Ubuntu container

You need a machine with Docker. Start a throwaway Ubuntu 26.04 container. Everything inside it runs as root, so the commands have no sudo.

docker run --rm -it ubuntu:26.04 bash

Inside the container, install nginx and curl. The image is a minimal install, so refresh the package lists first.

apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y nginx curl
nginx -v

nginx -v prints the version you are about to test. On Ubuntu 26.04 the archive package is built from nginx 1.28.3. The lab does not depend on whether the package also started an nginx service. It runs its own nginx process from its own config file, on port 8080, so it never touches the packaged default site.

The test configuration

Create a directory and write one self-contained config. It has five server blocks, all on 127.0.0.1:8080, so all five compete for the same requests. Each block returns a fixed label, which makes the answer easy to read.

mkdir -p /root/sn-lab
cat > /root/sn-lab/nginx.conf <<'EOF'
pid /root/sn-lab/nginx.pid;
events {}
http {
    access_log off;

    server {
        listen 127.0.0.1:8080 default_server;
        server_name _;
        return 200 "default\n";
    }
    server {
        listen 127.0.0.1:8080;
        server_name www.example.org;
        return 200 "exact\n";
    }
    server {
        listen 127.0.0.1:8080;
        server_name *.example.org;
        return 200 "leading-wildcard\n";
    }
    server {
        listen 127.0.0.1:8080;
        server_name mail.example.*;
        return 200 "trailing-wildcard\n";
    }
    server {
        listen 127.0.0.1:8080;
        server_name ~^(www|mail)\.example\.(org|net)$;
        return 200 "regex\n";
    }
}
EOF

The four named blocks overlap on purpose. www.example.org matches three of the four names. mail.example.org matches every name except the exact one. The regex covers www and mail under both .org and .net.

Test the file, then start nginx with it:

nginx -t -c /root/sn-lab/nginx.conf
nginx -c /root/sn-lab/nginx.conf

nginx -t checks the syntax and then tries to open the files the configuration refers to. A good file ends with a line saying configuration file /root/sn-lab/nginx.conf test is successful. The second command starts nginx in the background. If it reports that the address is already in use, another program holds port 8080. Pick a free port and change all five listen lines.

Send Host headers and read the answers

for h in www.example.org mail.example.org mail.example.net www.example.net www.sub.example.org example.org 127.0.0.1; do
  printf '%-20s ' "$h"
  curl -s -H "Host: $h" http://127.0.0.1:8080/
done

Each line prints the Host you sent and the label of the block that answered. Here is what the documented order predicts for each one, and why.

  • www.example.org should print exact. It also matches *.example.org and the regex, but the exact name is tried first.
  • mail.example.org should print leading-wildcard. It matches *.example.org, mail.example.* and the regex. A wildcard that starts with an asterisk ranks above one that ends with an asterisk, and both rank above any regex.
  • mail.example.net should print trailing-wildcard. *.example.org cannot match a .net name, so the trailing wildcard is the best match left, and it still beats the regex.
  • www.example.net should print regex. Only the regex matches it.
  • www.sub.example.org should print leading-wildcard. In nginx, the asterisk in *.example.org can match several name parts, so two labels in front of example.org still match.
  • example.org should print default. *.example.org needs at least one label in front of example.org, and no other name matches, so the default server answers.
  • 127.0.0.1 should print default. A request made to an IP address carries that IP in its Host header, and no block is named after it.

If your output differs from this list, trust your output for the version you installed, and write down nginx -v next to it. The list follows the nginx documentation, and the run is the proof.

Why there is no wildcard with an asterisk on both sides

A wildcard name may hold an asterisk only at the start or the end of the name, and only next to a dot. The nginx documentation calls www.*.example.org and w*.example.org invalid. No form allows an asterisk at both ends, so nginx does not accept *.example.* as a wildcard.

Watch nginx reject it. Change the trailing wildcard in the lab file to *.example.* and test again:

sed -i 's/mail\.example\.\*;/*.example.*;/' /root/sn-lab/nginx.conf
nginx -t -c /root/sn-lab/nginx.conf

nginx 1.28 stops with an error. After a timestamp, [emerg] and a process ID, the error names the bad wildcard and the address, and a second line reports the failed test:

invalid server name or wildcard "*.example.*" on 127.0.0.1:8080
nginx: configuration file /root/sn-lab/nginx.conf test failed

The cause is in the code that builds the name tables. It counts the asterisks in each name. A name with more than one asterisk is refused. A name with one asterisk is accepted only when that asterisk forms *. at the start or .* at the end. Everything else, including www.*.example.org, gets the same error.

Put the trailing wildcard back before you continue:

sed -i 's/server_name \*\.example\.\*;/server_name mail.example.*;/' /root/sn-lab/nginx.conf
nginx -t -c /root/sn-lab/nginx.conf

The regex that does the job, and where it ranks

To match one label, then example, then any one-label ending, use a regular expression:

server_name ~^[^.]+\.example\.[^.]+$;

[^.]+ matches one name part with no dot in it. So this regex matches www.example.org and shop.example.net, but not a.b.example.org. Keep the ^ and $ anchors, because without them the pattern can also match inside a longer name. Escape each dot with a backslash, because an unescaped dot matches any character. If a regex contains { or }, put the whole name in double quotes, or nginx fails to start.

This name ranks last. Any exact name, leading wildcard or trailing wildcard on the same address and port beats it. Among regex names, the first one in the configuration that matches wins. If one regex block catches requests meant for another regex block, move the more specific one higher in the file.

What .example.org means

The special form .example.org matches both the bare name example.org and every name under it, as *.example.org does. It saves writing two names. nginx stores it in the wildcard hash table, not in the exact-name table.

Do not put .example.org in one block and an exact example.org in another block on the same address and port. nginx 1.28 checks the bare part of .example.org against the exact names, so it sees the two as the same name. It keeps the one it reads first and ignores the second, with a warning from nginx -t. When the exact name comes second, the warning line starts with a timestamp, [warn] and a process ID, then gives this message:

conflicting server name "example.org" on 127.0.0.1:8080, ignored

The check still ends with test is successful, because a warning does not fail the test. So read the warnings. An ignored name means a block that never answers for that name. When .example.org is the one read second, nginx ignores the whole entry, so the subdomains stop reaching that block too. The same warning appears when two blocks on one address and port list the same exact name.

The default server is set on listen, not server_name

There is no way to set a default server with server_name. The default is chosen for each address and port, on the listen directive.

  • A block with default_server on its listen line is the default for that address and port.
  • If no block on that address and port says default_server, the first block for it in the configuration is the default.
  • Each address and port has its own default. One block can be the default on port 80 and an ordinary block on port 8080.
  • Only one block per address and port may say default_server. A second one stops nginx, and nginx -t reports a duplicate default server for 127.0.0.1:8080.

Now look at server_name _ in the lab. The underscore does nothing special. The nginx documentation calls it one of many invalid domain names that never match a real host, and says -- or !@# would work the same way. The lab's first block is the default because its listen line says default_server. Remove default_server and it stays the default only because it is the first block on 127.0.0.1:8080. Move it below the others as well, and the www.example.org block becomes the first block, so a request for example.org then prints exact.

A block with no server_name line gets the empty name, server_name "". That name lets the block handle requests that carry no Host header at all. To refuse requests that name no site you host, the nginx documentation uses its non-standard code 444, which closes the connection:

server {
    listen 80 default_server;
    server_name _;
    return 444;
}

Wildcard certificates follow different rules

nginx's *.example.org matches www.sub.example.org. A TLS (transport layer security) certificate for *.example.org does not. Under RFC 9525, a certificate wildcard must be the whole left-most label, and it matches exactly one label. So a *.example.org certificate covers www.example.org but not a.b.example.org. The bare example.org has no label in that position, so request it as a separate name on the certificate. A server block can therefore match a name that its certificate cannot serve, and browsers reject the certificate for that name even though nginx chose the right block.

Let's Encrypt issues wildcard certificates only through the DNS-01 challenge, and Certbot's standalone and webroot plugins cannot get them. The steps are in getting a wildcard certificate with Certbot and DNS-01. For a few named hosts on one server, Certbot with the nginx plugin on Ubuntu is the simpler path.

Clean up the lab

Stop the lab nginx and leave the container:

nginx -c /root/sn-lab/nginx.conf -s stop
exit

The --rm flag on docker run deletes the container when you exit, so nothing stays behind.

Apply the rules to your real server

On a running server, dump the full configuration that nginx loads, including every included file. Then read the listen and server_name lines together:

sudo nginx -T 2>/dev/null | grep -nE 'listen|server_name'

Group the blocks by listen address and port. In each group, find the default_server block, or the first block if none has it. Then walk the four ranks for the host name that misbehaves. After you edit, test and reload:

sudo nginx -t && sudo systemctl reload nginx

On a reload, the nginx master process checks the new configuration first. If the new file is invalid, it keeps running the old configuration. Confirm the result with the same curl method as the lab: curl -s -H "Host: www.example.org" http://SERVER_IP/ shows which block answers, without touching DNS.

The matching rules stay the same when a block passes traffic to an app. The nginx reverse proxy configuration guide covers what goes inside the block once nginx has chosen it. If you are still deciding which web server to run, compare nginx vs Caddy vs Traefik as a reverse proxy.

FAQ

Can an nginx server_name wildcard have an asterisk on both sides?

No. An asterisk is allowed only at the start or the end of a name, next to a dot. With *.example.* in a block that shares its port with other blocks, nginx -t fails with invalid server name or wildcard. Use a regex instead, such as ~^[^.]+\.example\.[^.]+$. Regex names are tried last, after exact names and both kinds of wildcard on the same address and port.

Why does nginx serve the wrong site for my domain?

The usual cause is that your block never took part in the name test. nginx first keeps only the blocks whose listen matches the address and port of the request, and only then compares names. If no name matches, the default server for that address and port answers: the block marked default_server, or the first block for that pair. Check the listen lines with sudo nginx -T, and run curl -H "Host: yourname" http://SERVER_IP/ to see which block answers.

Is server_name _ a catch-all in nginx?

No. The underscore is an invalid domain name that never matches a real host, and nothing more. A block catches unmatched requests only because it is the default server for its address and port. It gets that role from default_server on its listen line, or by being the first block for that address and port.

Does *.example.org match example.org in nginx?

No. *.example.org needs at least one label in front of example.org. It does match names several labels deep, such as www.sub.example.org. To match the bare name and its subdomains with one entry, write .example.org. A wildcard TLS certificate for *.example.org is stricter: it covers exactly one label, so it does not cover www.sub.example.org.

Was this article useful?

#nginx#server-blocks#virtual-hosts#regex#web-server