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

Nginx Server Block Returning 404? How to Fix a Second Virtual Host

A second NGINX site returning 404 is usually either the wrong server block or a bad URI-to-file mapping. This guide shows how to prove the cause and fix both cases, including HTTP/HTTPS, DNS, logs, permissions, and try_files.
Length10 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A second NGINX site normally returns 404 for one of two reasons: the request is being handled by a different server block, or the intended block maps the URL to a file that does not exist. Prove which block received the request before changing document roots. Check the effective configuration, test the exact Host value (including www), verify DNS, then check root/alias, location precedence, try_files, permissions, and the separate HTTPS configuration.

Why the second virtual host returns 404

NGINX does not choose a virtual host by the order of files in sites-available. It first groups server blocks by the address and port in their listen directives. Within that group, it compares the request’s Host value with each block’s server_name. If no name matches, NGINX sends the request to the default_server for that address and port, or to the first server declared for that listening socket when no explicit default is set.

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.

That means a 404 from the second domain may be generated by the first site’s block, a catch-all block, or another configuration entirely. The request can also reach the correct block and still fail later: root or alias can produce the wrong filesystem path, a file can be missing or unreadable, a nested location can override the expected settings, or try_files can deliberately finish with =404.

Server selection happens before filesystem lookup. Treat those as two separate questions:

#1 Best Overall
Recipe Book to Write in Your Own Recipes, Spiral Blank Cookbook 150 Recipes
  • B5 Recipe Book: This hardcover blank recipe book measures 10''×7.3'', containing 150 blank pages, comes with 1 sheet of DIY category stickers, perfect for writing down your own recipes and organizing them in one place.
  • Practical Layout - 5 pages of conversion charts show you everything you'll ever need to know in the kitchen. The table of contents will help organize your personal favorite recipes. A back pocket is designed for loose items.
  • Easy to Use - This blank cookbook is made of high-quality paper with a beautiful hardcover for long-term use. The sturdy gold double-wire spiral binding makes writing easier and page turning smoother.
  • Make Your Own Recipes - This blank cookbook has up to 150 blank pages for you to write in your own recipes, with plenty of space to record ingredients and instructions. You can write down all the special tips for your family members.
  • Thoughtful Gift - A personalized recipe book makes a thoughtful gift for your children or newlyweds, and a great gift for housewarming, weddings, bridal showers, anniversaries, or any other occasion.
  • Selection: Did the request for the second hostname reach its intended server block on the intended port?
  • Mapping: Once there, did the URI map to an existing, readable file or to the correct application fallback?

How NGINX selects a server block

The listening address and port come first

Only blocks listening on the same address and port compete with one another. Two sites can share an IP on port 80 because their names differ. They can also be deliberately separated by using different ports, but a block on port 443 cannot answer a request that arrived on port 80.

default_server belongs to the listen directive, not to server_name. For example, listen 80 default_server; makes that block the fallback for that listening address and port. It does not make a name match every hostname, and it does not affect port 443.

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

The Host value must match literally

The name comparison includes the exact hostname sent by the client. If the block lists second.example but the browser requests www.second.example, there is no match unless the latter is also listed. A request made to the server’s bare IP normally carries the IP as its host value, so it can select the default block instead of either named site.

For HTTPS, the TLS connection also has a server name indication (SNI) phase before the HTTP request. The certificate and the HTTP server selection still need to be configured for the 443 block. A working port-80 block does not configure 443 automatically.

Step-by-step diagnosis

1. Validate syntax before looking for behavioral fixes

Run a syntax check first. It does not reload NGINX and is safe to use while investigating:

sudo nginx -t

Do not proceed on a failed test. Correct the reported file and line, then run the command again. A successful test confirms parseable syntax, not that the desired block is enabled or selected.

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

2. Inspect the effective configuration, not just an individual file

Dump the complete configuration that the running binary can load:

sudo nginx -T

Search that output for every relevant directive:

sudo nginx -T 2>&1 | grep -E 'listen|server_name|root|alias|index|location|try_files|return|proxy_pass'

The dump includes files pulled in through include, so it reveals duplicate names, an unexpected default, a second 443 block, and a location that overrides a server-level setting. If you need to know which compiled paths and options the binary uses, inspect:

nginx -V

Pay particular attention to the prefix and configuration path reported there when troubleshooting a nonstandard installation.

3. Confirm that the intended site file is active

On Debian- and Ubuntu-style installations, a file in /etc/nginx/sites-available/ is only a definition. It becomes active when it is linked into /etc/nginx/sites-enabled/ (or otherwise included by the main configuration). Check both directories and the include lines shown by nginx -T:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
ls -l /etc/nginx/sites-available/
ls -l /etc/nginx/sites-enabled/

On distributions without those directories, find the actual include pattern in the configuration dump. A perfectly written file that is never included cannot receive traffic.

4. Compare the listen contexts and defaults

For two names sharing one IPv4 address, the usual arrangement is one server listening on port 80 for each name. Make sure both blocks use the intended address family and port, and that an accidental default_server is not masking the named block. Also inspect IPv6 listeners: a browser may resolve an AAAA record and reach an IPv6 block whose configuration differs from the IPv4 block.

If the sites are intentionally on different ports, test those ports explicitly. A request sent to port 80 cannot select a block that only listens on 8080.

5. Test the Host header without relying on DNS

From a client that can reach the server, send the second hostname explicitly to the server’s IP:

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

Test the www name separately:

curl -i -H 'Host: www.second.example' http://SERVER_IP/

These requests isolate NGINX name matching from public DNS. If the explicit hostname returns the expected site while the browser does not, investigate DNS, proxying, or browser caching. If it still returns the wrong site’s response, inspect server_name, listen, includes, and the default block.

For HTTPS, preserve the hostname in both SNI and the HTTP request while directing the connection to a particular IP:

curl -ik --resolve second.example:443:SERVER_IP https://second.example/

The -k option ignores certificate verification for this diagnostic only. Remove it when checking a production certificate. Use a matching --resolve entry for www.second.example if that is the name being tested.

6. Check DNS as a separate dependency

Once local host-header tests work, verify that the public name resolves to the intended address:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
dig +short second.example
dig +short www.second.example

Check both A and AAAA records when present. A correct NGINX file cannot answer a request that DNS sends to another host, load balancer, CDN, or old server. DNS changes can also remain cached according to their TTL, so compare the resolver result with the address you are testing.

Rank #2
Pipilo Press Blank Family Cookbook Recipe Binder - 6.5 x 8.2 in Hardcover Spiral Bound - 90 Ruled Pages with Memo Pocket - Write In Your Own Recipes & Meal Planning Notebook
  • Create a Culinary Legacy: The Pipilo Press Blank Family Cookbook Recipe Binder offers a timeless platform for chronicling beloved recipes. With its hardcover and spiral binding, this recipe book to write in your own recipes ensures durability and ease of use for generations
  • Thoughtful Gifting Choice: This book for writing recipes is an ideal present for various occasions, adding a personal touch to celebrations. Its elegant design makes it perfect for moms cookbook DIY projects or anyone passionate about preserving family traditions
  • Durable Design Features: Constructed with a 300gsm cardstock cover and matte lamination, this cookbook you can write in ensures longevity. Its spiral-bound format provides convenient access to pages, making it a practical tool for everyday use
  • Organized Recipe Storage: The included memo pocket offers a space to store handwritten notes or recipe cards, enhancing its functionality. This feature transforms the recipe book for moms into a sentimental family memento
  • Ample Writing Space: Measuring 6.5 x 8.2 inches, this blank spiral family recipe cookbook offers plenty of room for detailed notes. It is perfect for jotting down ingredients, preparation methods, and serving suggestions for a complete culinary record

7. Verify the root, alias, and actual files

Suppose the selected block contains:

root /var/www/second;

A request for /index.html maps to /var/www/second/index.html. Check that the path exists:

sudo ls -la /var/www/second/
sudo stat /var/www/second/index.html

NGINX must be able to traverse every parent directory and read the target file. Check directory execute permission, file read permission, ownership, and any mandatory access-control policy used by the operating system. A permission problem often appears in the error log; do not “fix” it by making the entire tree world-writable.

alias has different path-joining behavior and is especially sensitive to trailing slashes. For example:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
location /assets/ {
    alias /srv/second-assets/;
}

Here /assets/app.css maps to /srv/second-assets/app.css. Compare the requested URI and the resulting path character by character. A nested location may use a different root or alias than the server-level directive you inspected first.

8. Read access and error logs while reproducing the request

Use the paths configured by the active block or global logging directives. In one terminal, watch the logs; in another, repeat the explicit-host curl request. The access log can show the host, URI, status, and selected server fields when those fields are included in its log_format. The error log commonly exposes the file NGINX tried to open, a permission denial, a rewrite loop, or an upstream failure.

sudo tail -f /var/log/nginx/access.log /var/log/nginx/error.log

If the configured logs are elsewhere, obtain their paths from nginx -T. An access-log entry with the wrong host or an unexpected server name is strong evidence that the request selected another block; an entry with the right host and an open() path pointing at the wrong directory indicates a mapping problem.

9. Review location precedence and try_files

NGINX chooses the most specific prefix and regex location according to its location-matching rules. A nested block can therefore override the server’s root, index, rewrite behavior, or proxying. Inspect all locations that can match the failing URI, not only location /.

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.

This common pattern intentionally returns 404 when neither a file nor a directory exists:

location / {
    try_files $uri $uri/ =404;
}

That is appropriate for a static site when the URL must correspond to a real path. For an application router, the final candidate should instead be the documented fallback, such as a named location or an upstream, so that application routes are handled by the application rather than rejected as missing files. Do not remove =404 blindly; first decide whether the site is static or front-controller based.

10. Treat HTTP and HTTPS as independent configurations

Port 80 and port 443 have separate server-selection groups. Confirm all of the following in the 443 block:

  • listen 443 ssl; (and any required IPv6 listener) is present.
  • The second hostname appears in the 443 server_name.
  • The certificate and key cover the apex and any www name you serve.
  • The 443 block has the intended root, alias, locations, and application proxy.
  • An HTTP-to-HTTPS redirect points to the correct hostname rather than another site’s URL.

Use the --resolve command above to test 443 directly. A successful HTTP test does not prove that HTTPS uses the same document root or location rules.

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

11. Reload only after validation

Once the correction is made, validate and reload as one guarded operation:

sudo nginx -t && sudo systemctl reload nginx

A reload applies the new configuration without unnecessarily stopping the service. Repeat the explicit-host tests on both ports, then test through the real DNS names.

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

A minimal static configuration for a second site

This is a complete baseline for a static site. Adapt the paths and names to your server; do not copy it over an application configuration that needs a different fallback.

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

    root /var/www/second;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

The two server_name values cover the apex and www hostnames. The document root must contain the requested files, including index.html if the root URL is expected to work. try_files checks the URI as a file, then as a directory, and returns 404 when neither exists. If you add HTTPS, create and verify a corresponding 443 block rather than assuming this port-80 block will be reused automatically.

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.

Use a deliberate catch-all instead of silently serving another site

An explicit catch-all makes mistakes visible and prevents an unknown hostname from receiving the first site’s content:

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

The underscore is only a conventional, nonmatching name; it has no special catch-all behavior. The fallback role comes from default_server on the listen directive. Configure an equivalent policy for 443 if unmatched HTTPS traffic must also be rejected. During troubleshooting, a deliberate 404 from this block is useful because it proves the hostname did not match a named server.

Common symptoms and the corresponding fix

Symptom Most likely explanation What to verify
The first domain works; the second returns the first site’s 404 page The second hostname did not match, so the default or first block handled it. Exact Host, server_name, shared listen address/port, enabled includes, and the default block.
Testing by IP shows the wrong site The IP is the host value and normally selects the default block. Use curl -H 'Host: second.example' instead of a bare-IP request.
Explicit-host HTTP curl still returns 404, and logs show the right hostname The intended block was selected, but the URI maps to a missing or unreadable path. root/alias, actual files, parent-directory traversal, and error-log paths.
Only one URL path fails A more specific location, regex location, rewrite, or try_files rule handles that path. All matching location blocks and the final try_files argument.
HTTP works but HTTPS returns 404 Port 443 selected a different block or has different root/location rules. 443 listen, names, certificate/SNI, files, and curl --resolve.
Local tests work but the public domain fails DNS points elsewhere, an AAAA record reaches another host, or a proxy terminates traffic before NGINX. A and AAAA lookups, resolved address, proxy/CDN routing, and the server’s access log.
Configuration edits have no effect The edited file is not included, or NGINX was not reloaded. nginx -T output, nginx -t, and a successful reload.

Final verification checklist

  • sudo nginx -t succeeds.
  • sudo nginx -T shows the intended file and only the expected duplicate names.
  • The site definition is included or linked into the active configuration.
  • The second hostname, including www when used, appears in the correct server block.
  • The block listens on the port and address that receive the traffic.
  • An explicit HTTP Host test reaches the intended content.
  • DNS A and AAAA records resolve to the intended endpoint.
  • The configured root or alias resolves the URI to an existing, readable path.
  • Location precedence and try_files match the site’s static or application design.
  • HTTPS has its own verified 443 selection, certificate, root, and locations.
  • Logs confirm the expected host, URI, status, and filesystem or upstream behavior.
  • The validated configuration has been reloaded, and the real hostname has been tested again.

What to change first

Start with proof, not guesses: dump the effective configuration and send a request with the exact hostname. If that request is handled by the wrong block, fix the listen/server_name relationship or the enabled include. If it reaches the right block, follow the mapped path from URI to root or alias, check permissions and location precedence, and decide whether try_files should return 404 or pass the request to an application. Repeat the same proof on port 443 before declaring the second virtual host fixed.

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.

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
Outdated Drivers Are Slowing You DownFree scan - exact matches
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.