Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk13 min

How to Set Up Nginx Server Blocks and Fix Common Errors

A practical guide to NGINX server blocks: how request matching and defaults work, how to configure static sites, reverse proxies and HTTPS, and how to diagnose common errors with nginx -t and nginx -T.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a server block to give each hostname its own NGINX configuration. Define the address and port with listen, map hostnames with server_name, choose either a document root or an upstream application, test the complete included configuration with nginx -t, and reload only after the test passes. When NGINX shows the wrong site, inspect the active configuration with nginx -T, then check the request’s IP, port, Host header, DNS result, and default-server selection.

What an NGINX server block does

A server block is NGINX’s virtual-server unit inside the http context. It normally combines a listen directive, which selects an address and port, with server_name, which identifies the hostnames handled by that block. Other directives determine whether NGINX serves files directly or forwards requests to an application.

As an Amazon Associate I earn from qualifying purchases.

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.

One NGINX process can therefore handle several domains on one machine. Each domain can have its own root directory, redirect rules, proxy settings, logs, and TLS certificate. The block matters only if it is part of the configuration that the running NGINX process actually includes.

How NGINX chooses a server block

For every request, NGINX first narrows the candidates by the local address and port selected by listen. It then compares the request’s Host header with the server_name values on those blocks.

Name-matching priority

When multiple names could match, NGINX uses this order and stops at the first applicable result:

  1. Exact server name.
  2. Longest wildcard beginning with an asterisk, such as *.example.com.
  3. Longest wildcard ending with an asterisk, such as mail.*.
  4. The first regular-expression name in configuration order.

If no name matches, NGINX sends the request to the default server for that address and port. The default server is a property of the listen socket, not of a server_name. If no block explicitly declares default_server, the first block loaded for that address and port becomes the default.

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

Before you edit: find the active configuration

NGINX reads text configuration files, normally starting with nginx.conf. The main file contains include directives that pull in additional files. Distribution packages commonly provide directories such as conf.d or a sites-enabled layout, but directory names are not authoritative; the running configuration’s include graph is.

  1. Locate the configuration file used by the service manager. If the command is available, nginx -V shows the compiled-in path information.
  2. Open the active nginx.conf and identify the http block and every relevant include line.
  3. Choose a file that is included by that graph. Creating a file in an unreferenced directory has no effect.
  4. After editing, use nginx -T to print the complete parsed configuration. Confirm that your server block appears exactly once and that no earlier or later block unexpectedly defines the same name.

Set up a static website

For a site made of files, use root and usually index. This minimal block handles both the bare domain and its www name:

server {
    listen 80;
    server_name example.com www.example.com;

    root /var/www/example;
    index index.html;
}

What each directive controls

  • listen 80; accepts HTTP on port 80. Add an address if the host has several interfaces and you want to bind only one.
  • server_name example.com www.example.com; lists the hostnames this block should answer.
  • root /var/www/example; maps URL paths to files below that directory.
  • index index.html; tells NGINX which file to try for a directory request.

Make sure the directory and requested files exist and are readable by the NGINX worker process. A different location block can override the expected root, so inspect location rules when a file that exists still returns 404.

Set up a reverse proxy for an application

When an application process listens on its own address and port, put a location inside the server block and use proxy_pass. The deployment configuration also commonly uses proxy_set_header so the upstream receives the original host and client information.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
server {
    listen 80;
    server_name app.example.com;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

The port in proxy_pass must be where the application is actually listening. A server block can be syntactically correct while still returning 502 if the upstream process is stopped, bound to another address, or inaccessible. Check the process, test the upstream address from the NGINX host, and read both NGINX’s error log and the application’s log.

Make the block active safely

  1. Save the block in a file that the active configuration includes.
  2. Run nginx -t. This validates the complete configuration, including included files, rather than only the file you edited.
  3. Fix every reported error before proceeding. Do not reload after a failed test.
  4. After a successful test, reload through the service manager. A typical systemd command is sudo systemctl reload nginx; use the service-management command appropriate to your installation.
  5. Verify with a request that sends the intended hostname. For local testing, you can send the Host header explicitly: curl -i -H 'Host: example.com' http://127.0.0.1/.

Testing with the hostname is important: requesting the server’s IP alone may deliberately select the default block because the Host header does not match your site name.

Why NGINX serves the wrong site or a default page

1. The hostname resolves to the wrong address

Confirm that the domain’s DNS records point to the machine running NGINX. If DNS still points elsewhere, no server-block change on this host can affect the response. Check both IPv4 and IPv6 results; a browser may use an IPv6 address while your test uses IPv4.

2. The request reaches a different listen socket

Compare the request’s destination port and address with every listen directive. A block on port 80 cannot answer a request that arrives on port 443, and a block bound to one local address will not necessarily answer traffic sent to another.

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

3. The Host header does not match

An unmatched hostname, an IP-address request, or a request without a Host header goes to the default server for that socket. Add the exact name to server_name or deliberately define a catch-all block.

4. An unintended block is the default

Use an explicit declaration when you want predictable unmatched-host behavior:

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

The underscore is merely a conventional name that does not normally match a real hostname. It does not, by itself, make a block the default; default_server on listen does that.

5. Duplicate or shadowed names exist

Run nginx -T and search the output for the hostname. If it appears in multiple blocks on the same listen socket, remove the duplicate or make only the intended block authoritative. NGINX may report conflicting server name ... ignored and keep the first applicable definition, which can make an apparently correct edit ineffective.

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

HTTPS for one or more domains

An HTTPS block needs a TLS listener and valid certificate files. A basic pattern separates port 80 handling from port 443:

server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name example.com www.example.com;

    ssl_certificate     /etc/ssl/example/fullchain.pem;
    ssl_certificate_key /etc/ssl/example/privkey.pem;

    root /var/www/example;
    index index.html;
}

Several HTTPS names on one IP

Server Name Indication (SNI) lets multiple HTTPS names share one IP address. Give each HTTPS block the correct server_name values and certificate paths, and ensure clients reach the intended address. If SNI or name matching is wrong, NGINX can return the default server’s certificate instead of the certificate for the requested hostname.

Test the 443 configuration with nginx -t before reloading. Certificate and private-key paths must exist and be readable by the NGINX process; a missing file, invalid PEM data, or a mismatched key causes the test to fail.

Fix common nginx -t and startup errors

Message or symptom Likely cause Fix
nginx: [emerg] syntax error Missing brace or semicolon, a directive in the wrong context, or an error in an included file. Read the file and line named in the message, correct the syntax or context, then run nginx -t again.
conflicting server name ... ignored The same name is declared more than once on one listen socket. Search nginx -T, remove the duplicate, and keep the intended definition.
could not build the server_names_hash Names are too long for the current hash bucket or there are too many names for the current hash size. In the http context, increase server_names_hash_bucket_size for long names or server_names_hash_max_size for many names, then test again.
Certificate or key file error The path is wrong, the file is unreadable, or the certificate/key data is invalid. Correct the paths and permissions and verify the certificate and private key before re-running the test.
NGINX will not reload The configuration test failed or the service manager reported another startup problem. Run nginx -t, fix every reported issue, and inspect the service log before retrying.

Diagnose a 404, 502, or unexpected response

Static 404

  • Confirm the URL maps beneath the intended root.
  • Check that the file name and capitalization match the URL.
  • Verify readable permissions on every directory in the path and on the file.
  • Inspect more-specific location blocks that may override the root or rewrite the request.

Reverse-proxy 502

  • Confirm the upstream application is running.
  • Check that it is listening on the exact address and port in proxy_pass.
  • From the NGINX host, request that upstream address directly.
  • Read the NGINX error log for connection-refused, timeout, or name-resolution details, then inspect the application log.

Correct content only for some clients

Compare IPv4 and IPv6 DNS answers and listen directives. Also compare the Host header and destination port. Different network paths can reach different addresses, each with its own default block.

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

Choosing names, wildcards, and catch-alls

Approach Best fit Trade-off
Exact names A small, clearly audited set of domains. Every hostname must be listed explicitly.
Wildcard names Many subdomains that share behavior. Longest-wildcard matching can overlap with other names, so inspect priority carefully.
Regular expressions Patterns that cannot be represented by exact or wildcard names. They are evaluated later and in configuration order, making conflicts harder to reason about.
Explicit default server A deliberate response for unmatched or malformed hosts. It applies per address and port, so IPv4 and IPv6 sockets may need separate declarations.

Designing a maintainable server-block layout

Keep one clear responsibility per block whenever possible. A static site block should contain its document root and file-serving rules; an application block should contain its proxy location and upstream headers. Mixing unrelated hostnames in one block can be convenient initially, but it makes later certificate changes, redirects, and troubleshooting harder. Exact names are usually easiest to audit because you can search for every hostname and see its behavior directly.

Use wildcards only when the matching behavior really is shared. A wildcard such as *.example.com can cover many subdomains, but an exact name still has higher priority. If a subdomain later needs different content, add an exact-name block and confirm the resulting priority with nginx -T. Regular-expression names should be treated as an advanced option: they are checked after exact and wildcard names, and the first matching expression in configuration order wins.

Keep the HTTP and HTTPS versions of a site visibly related. The port 80 block can redirect to HTTPS, while the 443 block contains the content or proxy configuration. This separation makes it obvious which listener owns certificates and prevents accidentally placing TLS directives on a plain HTTP socket.

Use the effective configuration as your source of truth

Editing a familiar file is not proof that NGINX is using it. An include can be conditional on a different installation layout, a file can be duplicated in two included directories, or a package upgrade can change the service’s main configuration path. The nginx -T output shows the parsed files and their order, so it is the fastest way to answer “which block is actually loaded?”

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

When reviewing that output, search for all occurrences of the hostname, every listen line for the affected port, and each default_server. Check that an intended block is not followed by a duplicate declaration that triggers a conflict warning. Also confirm that the relevant include appears inside the http context; a server block placed outside its valid context produces an emergency configuration error.

Test routing independently of DNS

Separate name resolution problems from NGINX matching problems. First resolve the domain and confirm both address families point to the expected host. Then send a request directly to the local address with an explicit Host header, for example:

curl -i -H 'Host: example.com' http://127.0.0.1/

If that request returns the expected site but the public hostname does not, investigate DNS, an alternate IPv6 listener, a load balancer, or another machine in front of NGINX. If the direct request still returns the wrong site, inspect listen, server_name, duplicate declarations, and the default block in nginx -T.

Repeat the same separation for HTTPS by testing the 443 address and hostname, then checking which certificate is presented. A certificate for another domain generally indicates that the request reached a different default block or that the SNI name did not select the intended server block.

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

Understand server-name hash errors

NGINX stores names in an internal hash for efficient lookup. A very long hostname can exceed the configured bucket size, while a large collection of names can exceed the hash’s maximum size. These are configuration-build errors, not DNS failures. Place server_names_hash_bucket_size or server_names_hash_max_size in the http context, increase the setting that corresponds to the reported condition, and run nginx -t again. Do not put these directives inside an individual server block.

Operational checks after a reload

A successful syntax test confirms that NGINX can parse files and open referenced certificate paths; it does not prove that an application is healthy or that DNS has propagated. After reloading, make one request per hostname and port. Check the status code, the returned content, and, for HTTPS, the certificate name. For a proxied site, verify that the upstream process remains reachable after the reload.

When behavior differs from expectations, read the NGINX error log at the same time as the access log. The access entry confirms which request arrived; the error entry can identify an unavailable upstream, a permission problem, or a name-resolution failure. Application logs complete the picture for 502 responses because the proxy may be working while the application itself rejects or times out on the request.

A repeatable troubleshooting checklist

  1. Confirm DNS resolves the hostname to the intended IPv4 or IPv6 address.
  2. Confirm the request uses the expected port: 80 for HTTP or 443 for HTTPS.
  3. Check both address families and all matching listen lines.
  4. Verify the exact Host name is present in server_name.
  5. Run nginx -T and look for duplicate names, unexpected includes, and the actual default block.
  6. Run nginx -t and fix every error before reload.
  7. Reload NGINX only after a successful test.
  8. Use a request with an explicit Host header to isolate routing from DNS.
  9. For HTTPS, verify the 443 block, certificate paths, key paths, and SNI-related name matching.
  10. For 404 or 502 responses, follow the static-file or upstream checks above and read the relevant logs.

Frequently Asked Questions

How do I make one server block the default?

Add default_server to its listen directive, such as listen 80 default_server;. The default is selected per address and port. server_name _; alone does not make a block default.

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.

Why does NGINX serve the first site I configured?

If the Host header does not match any name on the socket, NGINX uses the first loaded block unless another block explicitly has default_server. Inspect nginx -T, then verify DNS, the destination port, and the Host header.

What is the difference between nginx -t and nginx -T?

nginx -t tests the complete configuration and reports syntax, path, listener, and certificate problems. nginx -T performs the test while printing the full parsed configuration, which helps reveal missing includes, duplicates, and unexpected defaults.

Can several HTTPS domains share one IP address?

Yes. Configure a separate 443 SSL server block and certificate for each hostname, and rely on SNI to select the name during the TLS handshake. Incorrect names, certificates, or default-server settings can result in the default certificate being returned.

Where should server-name hash directives go?

Put server_names_hash_bucket_size and server_names_hash_max_size in the http context, not inside an individual server block. Increase the bucket for unusually long names and the maximum size when there are many names.

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

Why does a valid static file return 404?

Check that the active block’s root maps the URL to the file, that capitalization matches, and that NGINX can read every directory and the file. A more-specific location rule may override the root or rewrite the request.

What causes a 502 from a reverse proxy?

The upstream process may be stopped, listening on another address or port, refusing connections, or timing out. Test the proxy_pass address from the NGINX host and inspect both NGINX’s error log and the application log.

Why does behavior differ over IPv4 and IPv6?

The two address families can resolve to different machines or match different listen sockets and defaults. Compare DNS answers, both sets of listen directives, and requests made to each address family.

The Bottom Line

Build server blocks around the request path NGINX actually uses: address and port first, hostname second, and the default block when no name matches. Keep each block included exactly once, choose root or proxy_pass deliberately, configure certificates on the 443 listener, inspect the complete setup with nginx -T, and run nginx -t before every reload. When something still looks wrong, isolate DNS, IPv4/IPv6, Host matching, file permissions, and upstream health one at a time.

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

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 *

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.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair 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.