Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › configuration

What `server_name` Does in an Nginx Configuration File

By Freedom251 Team · · 9 min read

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

server_name tells Nginx which host names a server { ... } block is responsible for. When multiple server blocks listen on the same IP address and port, Nginx compares the request’s host information with those names and chooses the matching block. The listen directive determines the socket; server_name determines the name match within that socket.

The role of server_name

Nginx can serve many websites from one IP address. Each website is usually represented by a server { ... } block, often called a virtual server or virtual host. The listen directive says where that block accepts connections, while server_name lists the host names that should select it.

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.
server {
    listen 80;
    server_name example.org www.example.org;

    root /var/www/example;
}

For an HTTP request such as GET / HTTP/1.1 with Host: www.example.org, Nginx first considers server blocks listening on the request’s address and port. It then tests the host value against the server_name directives in those blocks. The block whose name matches is used for the rest of request processing, including its root, proxy settings, rewrites, access rules and response behavior.

A name does not make a server reachable by itself. DNS still has to point the domain to the machine, and the block still has to listen on the address and port where the client connects. Conversely, a block can listen successfully but never receive a particular hostname if another block wins the name-selection step.

How Nginx chooses a server block

Selection happens in stages. The exact details differ slightly between plain HTTP and HTTPS, but the practical model is consistent: identify the listening socket, compare the request’s host information with candidate names, and use the highest-priority match.

1. Nginx narrows the candidates by address and port

Suppose one block has listen 192.0.2.10:80; and another has listen 192.0.2.10:443 ssl;. A request arriving on port 80 is not compared with the port-443 block. If several blocks share 192.0.2.10:80, they become candidates for the same socket.

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

Binding to a wildcard address such as listen 80; can also place a block on more addresses than an address-specific listener. When diagnosing an unexpected match, record the complete listening address, port, protocol options and whether a block is marked as the default.

2. Nginx compares the host name

For HTTP, the host normally comes from the Host header. Nginx compares that value with the names in the candidate blocks. A host can include a port, such as example.org:8080; the port is used to identify the connection, while the host name portion is what matters for name matching.

If a request has no usable host header, or its host does not match any configured name, Nginx falls back to the default server for that address and port.

3. The first matching category wins

Nginx does not simply use the last block in the file or the name that looks most specific to a human. It checks name categories in a fixed order:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Exact names.
  2. The longest wildcard that begins with an asterisk.
  3. The longest wildcard that ends with an asterisk.
  4. The first matching regular expression, in configuration-file order.

Once a category produces a match, Nginx stops searching lower-priority categories. Within a wildcard category, the longest matching wildcard wins. Regular expressions are different: the first matching expression in the configuration order wins, so moving regex-based server blocks can change behavior.

Exact names, wildcards and shorthand

Exact names

An exact name is the clearest and most predictable form:

server_name example.org www.example.org;

This block matches those two names, subject to the normal listening-address and port rules. Exact names take precedence over wildcard and regular-expression names when the same request could match more than one category.

Leading wildcards

A leading wildcard has an asterisk at the beginning, for example:

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.
server_name *.example.org;

It is intended for names below the domain, such as api.example.org or shop.example.org. Wildcards are restricted to the beginning or end of a name on a dot boundary; they are not arbitrary glob patterns that can replace characters in the middle of a label.

If several leading wildcards match, Nginx selects the longest one. For example, a request for v2.api.example.org can prefer *.api.example.org over *.example.org, because the former is the longer matching wildcard.

Trailing wildcards

A trailing wildcard places the asterisk at the end, such as:

server_name mail.*;

Trailing-wildcard matches are considered after exact names and leading wildcards. They are useful in narrowly controlled naming schemes but can be harder to reason about than explicit names, especially when several domains share the same configuration.

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

The dot shorthand

The compact name .example.org matches both example.org and names below it, including www.example.org. It is a convenient way to express an apex domain and its subdomains together:

server_name .example.org;

Use it only when the same server behavior is genuinely appropriate for the base domain and every subdomain. If different subdomains need different applications, list exact names or use separate wildcard blocks instead.

Regular-expression server names

A regular-expression name begins with ~ and uses PCRE syntax. For example:

server_name ~^user-(?<id>[0-9]+).example.org$;

The anchors ^ and $ require the entire host name to match, rather than allowing a matching fragment. Literal dots should be escaped as .; an unescaped dot in a regular expression means “any character.” Named or positional captures can be used by other Nginx directives, but introduce additional complexity and should be documented carefully.

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

Regex names are tested only after exact and wildcard categories. If more than one regex matches, Nginx uses the first matching expression in configuration-file order. Keep regex blocks together and order them from the most specific rule to the broadest rule so a later edit does not silently change which application receives a request.

Regex matching is powerful, but explicit names are usually easier to audit, test and secure. A typo in a regex can create an unintended match, and a broad expression may accept host names that you never intended to serve.

What server_name _; really means

Many configurations contain:

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

The underscore is a conventional name that is not expected to be a real domain. It has no special catch-all meaning in Nginx. The catch-all behavior in this example comes from default_server on the listen directive, not from server_name _;.

When no named server matches, Nginx sends the request to the default server for that address and port. The default is normally the first server listed for that socket, unless a block explicitly uses default_server. Therefore, this is also a valid way to make a block the fallback:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
server {
    listen 80 default_server;
    server_name invalid.invalid;
    return 444;
}

The name could be any value that does not conflict with a real request. Using an underscore is simply a widely recognized convention that signals “this block is for unmatched traffic.”

Only one default server can be selected for a particular address-and-port combination. If two blocks declare default_server for the same socket, Nginx reports a configuration error rather than choosing between them.

Why a request can reach the wrong virtual host

An unexpected response usually results from selection, not from the root directive itself. Check these causes in order:

  • The request arrived on a different socket. The client may be using port 443 while you inspected only port 80, or an address-specific listener may differ from the address you tested.
  • The host is not what you think. Test tools, proxies and load balancers can send a different Host value. An IP-address request, missing header or host with a port can select a fallback block.
  • An exact name beats your wildcard. A separate exact-name block may intentionally win over a broad wildcard.
  • A longer wildcard wins. A more specific leading wildcard can take precedence over a broader one.
  • A regex appears earlier. Among regex names, file order determines the winner.
  • The default server is different from the expected one. The first block for the socket may be the default because no block was marked explicitly.
  • The active configuration is not the file you edited. Included files and generated configuration can place another server block ahead of yours.

Inspect the complete loaded configuration with nginx -T, verify it with nginx -t, then reload only after the test succeeds. Send requests with an explicit host so that DNS and browser caches do not obscure the result:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -i -H 'Host: example.org' http://192.0.2.10/
curl -i -H 'Host: www.example.org' http://192.0.2.10/

For HTTPS, preserve certificate and SNI behavior while testing. A simple HTTP Host header test against port 443 does not reproduce the TLS handshake that a browser performs.

HTTPS: SNI comes before the HTTP host header

HTTPS adds an earlier selection point. During the TLS handshake, the client can send the requested host name using Server Name Indication (SNI). Nginx may use SNI to choose the TLS server configuration and certificate before an HTTP request exists. After the handshake, Nginx can select configuration again from the request line and Host header.

This means the names covered by your HTTPS certificates, SNI expectations and HTTP server_name blocks should agree. A certificate for one host combined with a server block intended for another can produce a certificate warning, an unexpected redirect or content from the wrong virtual server. Configure the same host set consistently on the relevant listen 443 ssl blocks and certificate definitions.

Clients that do not send SNI, or requests with no usable host information, follow the default-server behavior for the TLS socket. Keep the default HTTPS block deliberate: it may need to return an error or a neutral response rather than expose an unrelated site.

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

Name lists, redirects and the primary name

The first name in a server_name list is the primary server name:

server_name example.org www.example.org;

The server_name_in_redirect directive controls which name Nginx uses when it creates an absolute redirect. When that setting is enabled, redirects use the primary name. When it is disabled, Nginx uses the request’s Host value when one is present.

Choose the first name deliberately if your site has a canonical host. Then make redirects, cookies and application-generated URLs agree with that choice. Otherwise, clients can be bounced between equivalent names or see a redirect to a host that was not intended to be public.

Configuration limits and internationalized domains

Large name lists

Nginx stores server names in hash tables for efficient lookup. Very large or unusually long name lists can cause startup errors when the default hash sizing is insufficient. The relevant tuning directives are server_names_hash_max_size and server_names_hash_bucket_size.

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.

Do not increase these values blindly. First run nginx -t to capture the exact error, then adjust the hash settings in the appropriate http context and test again. Splitting an unwieldy list into clearer server blocks can also improve maintainability, provided the resulting precedence is intentional.

Internationalized domain names

Enter internationalized domain names in ASCII Punycode form in server_name. The browser may display a Unicode form to a user, but Nginx configuration should use the encoded ASCII label that appears in the DNS and HTTP representation. Verify the exact spelling, because visually similar Unicode characters can represent different names.

A practical configuration pattern

A common arrangement is to define an explicit default first, then exact-name application blocks:

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

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

server {
    listen 80;
    server_name api.example.org;
    proxy_pass http://127.0.0.1:9000;
}

Here, unmatched port-80 traffic goes to the default block. Requests for the two website names use the static site block, and the exact name api.example.org uses the API block. The separation is explicit: each block has one purpose, and no wildcard is needed.

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

If you later add *.example.org, remember that the exact API name still wins. If you add a regex, it will not override either exact name or matching wildcard; it is considered only when those categories do not match.

A diagnostic checklist

  • Confirm the client’s destination IP address and port.
  • List every server block listening on that address and port.
  • Record each exact, leading-wildcard, trailing-wildcard and regex name.
  • Check whether an explicit default_server exists; otherwise identify the first block for the socket.
  • Capture the actual HTTP Host value, including whether a port is present.
  • Apply precedence in order: exact, longest leading wildcard, longest trailing wildcard, then first regex.
  • For HTTPS, verify the SNI name, certificate coverage and post-handshake host selection separately.
  • Run nginx -T to inspect included files and nginx -t before reloading.
  • If startup reports a name-hash error, tune the documented hash directives rather than deleting names at random.

Once these checks are made, the apparently mysterious behavior of server_name becomes deterministic: the listener chooses the candidate set, the host name chooses the block according to fixed precedence, and the default server handles everything that remains.

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.

configurationHTTPSNGINXserver_namevirtual hostsweb servers

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.

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.