October DealsAmazon USOctober deal check: compare before you payAmazon 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 NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

How to Set Up NGINX Server Blocks and Fix Common Errors

Learn how NGINX selects server blocks, configure HTTP, reverse-proxy, and HTTPS hosts, and troubleshoot the errors that cause wrong sites, failed tests, bad certificates, 502s, and 404s.
Length13 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

NGINX server blocks let one NGINX instance host multiple websites or applications. Each block combines a listen address and port with one or more server_name values, then either serves files with root or forwards requests with proxy_pass. Create the block in a file that the active configuration includes, run nginx -t, reload only after the test succeeds, and use nginx -T when the running configuration does not behave as expected.

What an NGINX server block does

A server block is NGINX’s virtual-server unit inside the http context. It defines how requests for a particular address, port, and hostname should be handled. A simple static site normally needs listen, server_name, root, and index. An application server instead uses a location block with proxy_pass and suitable proxy headers.

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.

NGINX does not choose a block from the filename. It reads the complete configuration, including every file reached by an include directive, and then selects a block for each request. A file in a familiar directory such as sites-enabled or conf.d is useful only when the active nginx.conf actually includes that directory.

Keeping each host in its own clearly named file makes changes easier to review, but organization does not change routing. Context still matters: a directive valid in http may be rejected inside server, and a directive valid in server may not be valid in location. The parsed configuration, rather than the directory convention, is the authority.

How NGINX chooses a server block

Request selection happens in two stages:

  1. NGINX first compares the request’s local IP address and port with the listen directives.
  2. Among the blocks listening on that socket, it compares the HTTP Host header with server_name.

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 port, not of a server_name. A block becomes the default when its listen directive uses default_server; if none does, the first block for that address and port is used.

For a matching name, NGINX applies this priority and stops at the first matching category:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Exact name, such as play.example.com.
  2. Longest leading wildcard, such as *.example.com.
  3. Longest trailing wildcard, such as mail.*.
  4. The first matching regular expression.

Because regular expressions are evaluated last and can be difficult to audit, exact names are usually the clearest choice when you know every hostname. Wildcards are useful for predictable groups of subdomains, but overlapping patterns should be reviewed carefully. A request with no Host header, or a request made directly to an IP address, may not match the names you expect and can therefore reach the default block.

Before you edit anything

  • Find the active main configuration file, normally nginx.conf, and read its http-context include directives.
  • Confirm the hostname resolves to the server’s intended IPv4 or IPv6 address.
  • Decide whether the block will serve files directly or proxy to an application.
  • Check that the document root, certificate files, and upstream address will be readable and reachable by NGINX.
  • Record whether another block already uses the same hostname on the same listen socket.
  • Identify whether port 80, port 443, or another address and port is actually receiving the request.

When an installation behaves differently from its files on disk, the effective configuration is more reliable than assumptions about distribution layout. You can inspect it later with nginx -T. This is especially important after package upgrades, when a distribution may add a new include or leave an old example block enabled.

Set up a static website

1. Create the document directory

Place the site’s files in a dedicated directory, such as /var/www/example. Ensure the NGINX worker can traverse the directories and read the files. Put an index.html file in the directory if you want the default index directive to return a page.

2. Add the server block

Use a block like this in a file that the running configuration includes:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example;
    index index.html;
}

listen 80 handles HTTP on port 80. The two names are both exact names that will route to this block. root maps the requested URI to a file below the specified directory, and index tells NGINX which file to try for a directory request.

3. Make sure the file is included

Some packages provide a site-available/site-enabled arrangement; others use a conf.d include. Do not rely on the directory name. Check the active nginx.conf and its nested includes. If the block does not appear in the parsed configuration, NGINX cannot use it.

4. Test, reload, and verify

  1. Run nginx -t. This validates the complete included configuration, not just the file you edited.
  2. Correct every reported brace, semicolon, context, path, duplicate-listener, or certificate error.
  3. After a successful test, reload NGINX through the host’s service manager. On a systemd installation, the usual command is systemctl reload nginx.
  4. Request the hostname and confirm the expected page is returned. A direct test against the local listener can supply the intended host header: curl -H "Host: example.com" http://127.0.0.1/.

A reload applies the new configuration without requiring a full stop and start. If the test fails, do not reload; the old working configuration should remain in service while you fix the error.

Set up a reverse-proxy server block

For an application running separately from NGINX, keep the public listener in the server block and proxy matching requests to the application process:

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 {
    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 important configuration surface is the location, proxy_pass, and proxy-header directives. The upstream process must be running and reachable at the address in proxy_pass. If the application listens on another address, socket, or port, use that exact endpoint and test it independently before debugging NGINX.

The forwarded headers preserve information that would otherwise be lost at the proxy boundary. The application receives the original host, client address, chain of forwarding addresses, and whether the public request used HTTP or HTTPS. Make sure the application is prepared to trust those headers from NGINX; changing the proxy target alone will not repair an application that is stopped, listening on a different interface, or returning an invalid response.

Configure HTTPS for one or more domains

Use separate HTTP and HTTPS handling

A common arrangement has one block on port 80 and another on port 443. The port-80 block can redirect HTTP or provide another deliberate response; the port-443 block terminates TLS and serves or proxies the site.

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/nginx/tls/example/fullchain.pem;
    ssl_certificate_key /etc/nginx/tls/example/privkey.pem;

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

The HTTPS block needs listen 443 ssl, the intended names, a valid certificate path, and a valid private-key path. The certificate must cover every hostname listed in that block. A certificate file can exist and still be wrong if it does not contain the requested name.

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

Host several HTTPS names on one IP

Server Name Indication (SNI) allows multiple HTTPS sites to share one IP address. Create a 443 block for each certificate/name set, make sure the names and certificate files correspond, and ensure the request reaches the intended 443 listener. If SNI or name matching is wrong, a browser can receive the certificate from the default server instead of the certificate intended for the requested hostname.

Keep the 443 names unambiguous. A duplicate name on the same socket can be ignored with a warning, leaving an apparently valid certificate attached to a block that never answers. Inspect all 443 listeners and certificate directives in nginx -T whenever a browser reports the wrong certificate.

Check IPv4 and IPv6 listeners

Different results over IPv4 and IPv6 often mean that only one family was configured or that each family has a different default block. Review both forms of the listen directive, such as an IPv4 listener and an IPv6 listener, and verify DNS records for both address families.

Why NGINX serves the wrong site

The request does not match the expected name

Confirm that the browser or client sends the exact hostname in the Host header, including whether it uses a www prefix. A DNS record pointing elsewhere, a typo in server_name, or a request made by IP address can all lead to a different block.

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

The default server is catching unmatched traffic

To make unmatched requests predictable, designate an intentional catch-all:

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

The underscore is merely a conventional name that is unlikely to match a real hostname. It is the default_server parameter on listen that makes this block the default; server_name _; alone does not.

Remember that the default is per address and port. A default on IPv4 port 80 does not automatically become the default on IPv6 port 80, nor does an HTTP default control HTTPS traffic on port 443. Set deliberate defaults for each socket where unmatched requests need the same treatment.

Duplicate names or hidden includes override expectations

If two blocks use the same name on the same address and port, the result can be a warning and an unexpected winner. Run nginx -T and search its complete output for every occurrence of the hostname, every relevant listen directive, and every included filename. Remove obsolete blocks or make one block the authoritative definition.

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

The IP and port differ from what you tested

NGINX first selects by local address and port. A block listening on one address does not automatically handle traffic arriving on another. Compare the destination address used by the client with all listen directives, and check IPv4 and IPv6 separately.

Fix common NGINX errors

nginx: [emerg] syntax errors

An emergency-level startup error prevents the new configuration from loading. Check balanced braces, terminating semicolons, misspelled directives, and whether each directive appears in a context where it is allowed. Included files can be the source even when the main file looks correct. Run nginx -t after each correction until it reports a successful test.

nginx -t reports a bad path or certificate

For a root, certificate, or key error, verify the path character by character, confirm the file exists, and check permissions on the file and every parent directory. An HTTPS block cannot load if its ssl_certificate or ssl_certificate_key path is wrong or unreadable. Correct the path, test again, and reload only after success.

conflicting server name ... ignored

This warning means a name is defined more than once for a relevant listen socket. Locate all copies with nginx -T, then remove the duplicate, narrow one block’s names, or move the intended name to the block that should answer requests. Leaving the warning unresolved makes the selected site dependent on configuration order.

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

could not build the server_names_hash

NGINX stores server names in a hash. Very long names can require a larger server_names_hash_bucket_size; a large number of names can require a larger server_names_hash_max_size. Set these directives in the http context, not inside an individual server block, then run nginx -t again. Increase only the setting named by the error and retest.

502 Bad Gateway from a proxy

A 502 generally means NGINX could not obtain a valid response from the upstream. Check that the application process is running, that it listens on the address and port in proxy_pass, and that local firewall or socket permissions do not block access. Read the NGINX error log and the application’s own logs together; the upstream error usually identifies whether the cause is refusal, timeout, or an invalid response.

Static files return 404

Confirm that root points to the directory you intended, that the requested file exists at the resulting path, and that NGINX can read it. Review nested location rules because a more specific location can change how the URI is mapped or override the expected root. Test a known file directly before troubleshooting application routing.

The browser shows the wrong HTTPS certificate

Check the 443 listen directives, the requested hostname, certificate coverage, and SNI-related name matching. Inspect nginx -T for duplicate 443 names and identify which block is the default for that socket. A valid certificate on the wrong block still produces the wrong certificate for the client.

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

Understand the effective configuration

When a block appears correct but has no effect, separate three questions: was the file included, did the configuration test pass, and did the request reach the socket you edited? nginx -T answers the first question by printing the complete parsed configuration, including included files. Search that output for the hostname, its listen port, duplicate definitions, certificate paths, and any catch-all block.

Use nginx -t after every meaningful change, including edits to an included file. A successful test confirms that NGINX can parse the complete configuration and access referenced resources well enough to load it. It does not prove that DNS points to this machine or that an upstream application is healthy, so verify those separately.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose the right configuration pattern

Decision Use this pattern Important implications
Static site or downloadable files root with index NGINX reads files directly; verify path and read permissions.
Application server location with proxy_pass and proxy headers The upstream must be running and reachable; a failure commonly appears as 502.
Known individual hostnames Exact server_name values Easiest to audit and least likely to overlap.
Predictable subdomain family Wildcard names Longest matching wildcard wins; overlapping patterns need review.
Specialized dynamic matching Regular-expression names Evaluated after exact and wildcard names and can be harder to reason about.
Encrypted traffic listen 443 ssl with certificate and key paths SNI and correct name-to-certificate mapping are required for multiple HTTPS sites.
Unmatched or hostile hostnames Explicit default_server Defines deliberate behavior instead of relying on whichever block appears first.

A repeatable troubleshooting workflow

  1. Identify the destination IP and port used by the failing request.
  2. Confirm DNS points the hostname to that destination, checking IPv4 and IPv6 independently when applicable.
  3. Inspect the relevant listen and server_name directives.
  4. Run nginx -T to view the complete parsed configuration, including nested includes and duplicate blocks.
  5. Check whether the hostname is exact, wildcard, or regular-expression matched, and apply the documented priority order.
  6. Determine which block is the explicit or implicit default for that socket.
  7. Run nginx -t and fix every error before reloading.
  8. Reload through the service manager only after the test succeeds.
  9. Verify with a request carrying the intended Host header, then inspect NGINX and upstream logs if the response is still wrong.

Operational checklist

  • Keep one authoritative definition for each hostname and listen socket.
  • Use exact names unless a wildcard solves a real maintenance problem.
  • Make the catch-all block explicit rather than depending on file order.
  • Test the complete configuration after every edit, including edits to included files.
  • Keep HTTP and HTTPS behavior in clearly identifiable blocks.
  • Match every HTTPS name to the certificate that covers it.
  • Use nginx -T whenever the active behavior does not match the file you expected NGINX to read.
  • Treat syntax, certificate, listener, and upstream errors as deployment blockers until nginx -t passes.

Frequently Asked Questions

Why is NGINX serving the default page instead of my website?

First confirm DNS points to the intended server and that the request uses the expected hostname. Then compare the destination IP and port with listen, inspect every matching server_name in nginx -T, and check which block is the default for that socket. A missing Host header, an IP-based request, a duplicate name, or an IPv4/IPv6 mismatch can all send traffic to the default block.

Does server_name _; make a block the default?

No. The default_server parameter on the relevant listen directive makes a block the default. The underscore is only a conventional nonmatching name. If no block explicitly uses default_server, NGINX uses the first block for that address and port.

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

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

nginx -t tests whether the complete included configuration can be parsed and loaded. nginx -T prints that effective configuration, which helps find hidden includes, duplicate server names, unexpected listeners, and the certificate or default block actually in use. Run the test before every reload.

Why does NGINX report “conflicting server name … ignored”?

The same hostname is defined more than once on a relevant listen socket. Use nginx -T to locate every definition, remove obsolete or duplicate entries, narrow one block’s names, or move the name to the block that should answer requests. Leaving the warning can make routing depend on configuration order.

How do I host several HTTPS domains on one IP address?

Create a 443 server block for each domain or certificate set, use listen 443 ssl, list the correct names, and provide matching ssl_certificate and ssl_certificate_key paths. SNI lets NGINX select among HTTPS names on one IP, but duplicate names, incorrect DNS, or a wrong default block can still produce the wrong certificate.

Where should server-name hash settings go?

Place server_names_hash_bucket_size or server_names_hash_max_size in the http context, not inside an individual server block. Increase the setting named by the error, run nginx -t, and reload only after the test succeeds.

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.

What should I check when a reverse proxy returns 502?

Verify that the upstream application is running, listening on the exact address and port in proxy_pass, and reachable by NGINX. Check socket or firewall permissions, then read the NGINX error log and the application’s logs together. The upstream message usually distinguishes refusal, timeout, or an invalid response.

Why do static files return 404 even though the server block is loaded?

Confirm that root points to the intended directory and that the requested file exists at the URI-derived path. Check read and directory-traverse permissions, and inspect nested location rules because a more specific location can override the expected mapping. Test a known file before investigating application routes.

The Bottom Line

Build each server block around the correct listen socket and exact server_name, ensure the file is included, and test the complete configuration with nginx -t before reloading. When routing, HTTPS, or proxy behavior is surprising, use nginx -T to inspect the effective configuration, then verify DNS, IPv4/IPv6 listeners, defaults, certificates, and upstream reachability in that order.

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.

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.

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
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.