Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 30 ยท Nginx Configuration

Server Blocks and Choosing a Server

Learn Nginx server blocks: listen and server_name, exact, wildcard and regex names, default_server, the order Nginx uses to pick a server and a catch-all that drops unknown hosts.

One Nginx instance usually serves many sites. Each site is a server block, and every incoming request has to be matched to exactly one of them. If you have ever typed your server's IP address into a browser and landed on the wrong website, or added a new domain and seen it show another site's content, you have met this selection process. It follows precise rules, and knowing them takes the mystery out of the most common "why is the wrong site showing?" problem.

Real Nginx cannot run inside this page, so the real configuration is read-only. The runnable stand-in is a JavaScript function that implements the selection algorithm, so you can test any combination of address, port and Host header yourself.

Anatomy of a server block

A server block says which connections it accepts (listen), which site names it answers to (server_name) and what to do with the requests (everything else):

NGINX
server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example;
    index index.html;
}

server {
    listen 80;
    server_name blog.example.com;
    root /var/www/blog;
}

Both servers listen on port 80. A request arrives with a Host header (Host: blog.example.com), and Nginx compares that name with each server_name to decide which block handles it. The Host header is part of HTTP itself (What a Web Server Does): the browser takes it from the address you typed.

The listen directive

listen takes an address, a port, or both, followed by optional flags:

NGINX
listen 80;                       # all IPv4 addresses, port 80
listen 443 ssl;                  # port 443 with TLS
listen 127.0.0.1:8080;           # one address only
listen [::]:80;                  # all IPv6 addresses
listen 80 default_server;        # this server is the fallback for port 80
listen unix:/run/site.sock;      # a Unix domain socket

If you write only a port, Nginx binds the wildcard address on that port. If you omit listen entirely, a server block listens on port 80 (or 8000 when Nginx runs without root privileges), which makes forgetting it a quiet bug.

server_name forms

server_name accepts one or more names, and they come in four kinds:

Form Example Matches
Exact www.example.com exactly that name
Leading wildcard *.example.com a.example.com, a.b.example.com, but not example.com
Trailing wildcard www.example.* www.example.com, www.example.org
Regular expression ~^(?<user>.+)\.example\.com$ whatever the regex matches

Two conveniences are worth knowing. The special form .example.com matches both example.com and every subdomain, which saves you from listing example.com and *.example.com separately. And a regular expression name starts with a tilde; if it contains named captures such as (?<user>...), the captured text becomes a variable ($user) you can use later in the block. Wildcards may only have the * at the very start or very end of the name, and never in the middle. Names are compared case-insensitively.

How Nginx picks a server

Nginx makes the decision in two steps.

Step 1: pick by address and port. The connection arrived at a particular address and port (for example 203.0.113.5:80). Nginx finds the servers whose listen matches. A listen with a specific address beats a wildcard listen on the same port.

Step 2: pick by name, among those servers. Nginx takes the Host header (ignoring any :port suffix) and tests the names in a fixed order and stops at the first success:

  1. An exact name.
  2. The longest wildcard starting with *, such as *.example.com.
  3. The longest wildcard ending with *, such as www.example.*.
  4. The first matching regular expression, in the order they appear in the configuration file.
  5. If nothing matched: the default server for that address and port. It is the one marked default_server on its listen, or, if none is marked, the first server defined for that address and port.

Choosing a server

Address and port Narrow down by the listen directive.
Exact name www.example.com beats any wildcard.
Longest wildcard First the leading star, then the trailing star.
First regex Config order decides between regexes.

Nothing matched? The default server takes the request.

1 / 2

The consequences are practical. A visit to your server by raw IP, or through a domain you never configured but that points at your machine, carries a Host header that matches nothing, so the default server answers. If that is your real site, then other people's domains pointed at your IP will show your content, and scanners hitting your IP will see it too. That is why most production configurations define a deliberate catch-all.

A catch-all that drops unknown hosts

NGINX
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;               # not special: just a name nothing will ever send
    return 444;                  # Nginx-specific: close the connection with no response
}

The name _ is only a convention: it is a valid name that no real client sends, so it never matches anything and the block serves purely as the default. Status 444 is a non-standard Nginx code that closes the connection without sending a response. For HTTPS, the equivalent is to reject the TLS handshake in the default server with ssl_reject_handshake on; (available in recent versions), since otherwise a certificate must be presented before the Host header is even known. You will build on this in HTTPS, TLS and Let's Encrypt.

Testing from the command line

You do not need DNS to test which server answers. Send the Host header yourself:

Terminal
curl -I -H "Host: blog.example.com" http://127.0.0.1/
curl -I --resolve blog.example.com:80:127.0.0.1 http://blog.example.com/

The first sends a custom Host header to the loopback address. The second tells curl to pretend that the name resolves to that address. Remember that the Host header is chosen by the client: it is not authentication, so never treat "the Host header said so" as proof of anything.

Simulation: the selection algorithm

This script implements the algorithm above. A server is a name, a list of listen entries (address, port, whether it is default_server) and a list of server_name values. pickServer returns the server and explains how it decided. We test it with a set of requests:

JS Which server answers this request?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Study a few results. blog.example.com matches the exact name in A even though the wildcard in B would also match, because exact names win. shop.example.com has no exact name, so the wildcard B wins. app42.example.com is also matched by B's wildcard, and because wildcards are tried before regular expressions, the regex server D never gets it. That ordering surprises many people: a broad wildcard shadows a more specific regex. www.example.org falls to C through the trailing wildcard www.example.*. The raw IP address matches nothing and lands on F. And the request that arrives at the specific address 10.0.0.5 takes only the servers listening on that address, so E is the default there and the others never see it.

Checking what you actually have

Two practical ways to inspect a real server:

Terminal
sudo nginx -T | grep -E "server_name|listen"
curl -s -o /dev/null -w "%{http_code}\n" -H "Host: unknown.example" http://127.0.0.1/

If the second command returns the status of your real site, you do not have a catch-all. Also watch for duplicate names: two servers on the same address and port with the same server_name make Nginx warn "conflicting server name" at test time and ignore the second one. A warning from nginx -t here almost always means a site is not doing what you expect.

Simulation: add a catch-all and see who is shadowed

Our second script runs the same idea in reverse: given a set of servers and an exhaustive list of hosts people might send, it reports which servers would never be selected. These are the dead blocks you want to find before a customer does. To keep the example short it includes only exact and default selection:

JS Find servers that never answer

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The server old repeats a name that main already owns, so it never answers, exactly the situation behind the "conflicting server name" warning. The empty host (a request with no Host header, as HTTP/1.0 clients may send) goes to the default.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A request has Host: shop.example.com. One server has server_name *.example.com and another has a regex ~^shop..+$. Which wins?

    Nginx tries exact names, then leading wildcards, then trailing wildcards, and only then regexes. The wildcard matches first and the regex is never consulted.
  2. 2. What answers a request whose Host header matches no server_name on the listening address and port?

    The unmatched request is handed to the default server for that address and port. If none is marked default_server, the first server defined there is used.
  3. 3. What does the name _ mean in server_name _;?

    The underscore has no special meaning to Nginx. It is simply a name that never matches real traffic, so the block acts only as the default.
  4. 4. Which pattern matches both example.com and any subdomain of it?

    A name starting with a dot, .example.com, is shorthand for example.com plus *.example.com.

Summary

  • A server block is a site; listen chooses the connections it accepts and server_name the Host names it answers to.
  • Selection is two steps: choose by address and port (a specific address beats a wildcard), then by name: exact, longest leading wildcard, longest trailing wildcard, first matching regex, then the default server.
  • The default server is the one marked default_server, or else the first server defined for that address and port.
  • .example.com covers the apex and all subdomains; wildcards may only have * at the start or the end.
  • Use a deliberate catch-all (default_server, server_name _;, return 444;) so unknown hosts do not reach a real site.
  • Test with curl -H "Host: ..." or --resolve, and heed "conflicting server name" warnings.

Next: Location Blocks and Matching Order