October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk11 min

How to Fix Nginx Server Blocks That Work Only Intermittently

Nginx usually is not choosing a server block randomly. Learn how listener order, Host matching, IPv4/IPv6, TLS SNI, defaults, and upstream health create intermittent results—and how to prove and fix each cause.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When an Nginx server block works only sometimes, Nginx is usually making a consistent choice that differs between requests. The common causes are incomplete IPv4/IPv6 listeners, a different Host value, an unexpected default server, overlapping server_name patterns, TLS/SNI differences, or an upstream that is temporarily unavailable. Fix the selection path first, then investigate proxy timing and backend health.

How Nginx chooses a server block

Nginx does not search every configuration file for the most appropriate site on every request. It builds listening sockets and then selects a virtual server in a defined sequence.

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.

1. The listening address and port come first

Each listen directive contributes an address-and-port combination, such as IPv4 port 80, IPv6 port 80, or IPv4 port 443. A request arriving on a socket that your intended block does not cover cannot be selected by that block, even if its hostname appears in server_name.

IPv4 and IPv6 are separate paths. If DNS publishes both an A record and an AAAA record, clients can reach different sockets depending on their network, operating system, resolver, or connection preference.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

2. The Host header is compared on that socket

When multiple server blocks share an address and port, Nginx compares the HTTP Host header with their server_name values. Exact names, wildcard names, and regular expressions have a defined priority. An exact name wins first; then the longest matching wildcard; then regular expressions in configuration order.

3. Unmatched requests use the default server

If no server_name matches, or the request has no Host header, Nginx sends it to the default server for that listening port. The default is the first server listed for that socket unless a block explicitly uses default_server. File names and directory names do not determine this order; the fully loaded configuration does.

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 the failure looks intermittent

Dual-stack DNS sends clients down different paths

A hostname with both A and AAAA records can reach an IPv4 block that is correctly configured while IPv6 reaches a different block, the distribution’s default page, or no listener at all. The same user may see different results after switching networks because one network has working IPv6 and another does not.

Multiple addresses produce different results

Round-robin DNS, a load balancer, or stale DNS can direct requests to different servers. If only one machine has the updated block, the hostname appears unreliable even though each machine is internally consistent.

The request carries a different name

Users may enter an alias, a bare domain, a www name, an old subdomain, or an internal hostname. Redirects can also change the host or port. A block containing only example.com does not match www.example.com unless that alias is listed.

TLS can select a different block before HTTP

On HTTPS, the client sends a TLS Server Name Indication value before Nginx can process the HTTP Host header. A missing or incorrect SNI value can cause the certificate and TLS server block to come from the default listener. After the handshake, an HTTP host mismatch can still select an unexpected block, so port 443 requires consistent names, certificates, redirects, and listeners.

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

The right block can proxy to an unreliable upstream

A correct server selection does not guarantee a successful response. Nginx may fail to connect to an upstream, wait for response headers, or retry another upstream after a communication error. Passive health behavior can mark a repeatedly failing upstream unavailable for a period controlled by fail_timeout. That produces intermittent 502, 504, or delayed responses even when routing is correct.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

The edited file may not be active

A file can be syntactically valid yet ignored because its directory is not included, a different configuration prefix is in use, or the service was never reloaded. Always inspect the complete running configuration rather than assuming the file you edited is loaded.

Step 1: Render and inspect the active configuration

Run the commands as the account that can read the deployed Nginx configuration, using the service’s actual binary path if it is not on PATH.

nginx -T 2>&1 | less
nginx -t

-T prints the complete configuration after includes are expanded. Search that output for every relevant listen, server_name, default_server, and include. The test command checks syntax and basic configuration validity but does not prove that a request will select the intended block.

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.

Look for these specific configuration defects

  • The intended block has only listen 80; while clients also arrive on IPv6.
  • Another file declares default_server on the same address and port.
  • Two blocks claim the same exact name, or a broad wildcard captures traffic you expected an exact name to receive.
  • The intended file is outside an active include pattern.
  • Port 80 and port 443 have different aliases, defaults, or redirect targets.
  • A separate Nginx instance or container is serving the public address.

There can be only one explicit default for a given address-and-port socket. If you need separate IPv4 and IPv6 sockets, designate the intended fallback on each one.

Step 2: Test every address while preserving the hostname

First resolve the public name and record every A and AAAA address returned by your resolver. Test each address separately while sending the hostname that should select the site.

dig +short A example.com
dig +short AAAA example.com
curl -4 -v --resolve example.com:80:203.0.113.10 http://example.com/
curl -6 -v --resolve example.com:80:2001:db8::10 http://example.com/

Replace the example addresses with the actual results. The --resolve option connects to the specified address but keeps the URL hostname, so the HTTP Host value remains meaningful. Repeat the test on HTTPS:

curl -4 -vk --resolve example.com:443:203.0.113.10 https://example.com/
curl -6 -vk --resolve example.com:443:2001:db8::10 https://example.com/

Use -k only while diagnosing certificate behavior; do not treat it as a production fix. Compare status codes, response headers, certificate names, redirects, and response bodies. A difference between -4 and -6 points to listener, firewall, DNS, or address-specific configuration rather than random application behavior.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Test aliases and an unmatched name

Call every public alias exactly as a user would, including the bare domain, www form, API hostname, and any redirect destination. Then deliberately send an unknown host to see which block is the fallback.

curl -v -H Host:unknown.example http://203.0.113.10/

If the unknown host returns a real site’s content, the default server is not an intentional rejector. In a multi-site deployment, use a dedicated default block that returns a controlled status instead of exposing another site’s content.

Step 3: Make listener coverage explicit

A typical dual-stack HTTP block needs an IPv4 and an IPv6 listener:

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    # locations, redirects, or proxy settings
}

For HTTPS, configure both families on port 443 and ensure the certificate covers every name:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
server {
    listen 443 ssl;
    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;
}

Do not add an IPv6 listener merely to silence a symptom if the host has no IPv6 route or firewall rule. Confirm that the address is assigned, port 80 or 443 is permitted, and the same configuration is deployed on both paths.

Step 4: Define the fallback deliberately

The first listed server becomes the default when no explicit default exists. That makes behavior depend on include order, which can change when files are added or renamed. Declare the intended fallback instead:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;
    return 444;
}

The underscore is a conventional non-domain name; it is not a magic wildcard. The important parts are the explicit defaults and a response policy. You may return a normal 400 or 404 instead of Nginx’s non-standard 444 if clients, monitoring, or compliance tools need a conventional HTTP response.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Place real sites in separate blocks with their exact names and required aliases. Do not rely on a broad wildcard as a substitute for listing known names when a typo should be rejected.

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

Step 5: Audit server_name matching

Prefer exact names for primary sites

List the canonical hostname and each supported alias explicitly:

server_name example.com www.example.com api.example.com;

Use a wildcard only when the application genuinely serves a family of names. A leading wildcard such as *.example.com does not match the bare example.com; include that name separately if required.

Treat regular expressions as an ordered rule set

Regular-expression names are considered after exact and wildcard matches, and the first matching expression in configuration order wins. A newly added expression can therefore change an older site’s behavior without changing either site’s URL. Keep regex rules narrow, document their purpose, and place them after exact-name blocks.

Normalize canonical redirects

Decide whether the canonical URL uses the bare domain or www, HTTP or HTTPS, and one preferred port. Put redirects in blocks that cover every address family and alias. A redirect target that is absent from server_name can send users into a default block and make the original failure appear random.

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

Step 6: Use logs to prove which block handled a request

Nginx’s access and error logs are the fastest way to distinguish selection from backend failure. During reproduction, watch the logs for the exact client request and timestamp:

tail -F /var/log/nginx/access.log /var/log/nginx/error.log

Paths vary by distribution and by the access_log and error_log directives in your configuration. Give each virtual host a distinct access-log file when possible. Include the hostname and timing fields in a diagnostic format:

log_format routed '$remote_addr host=$host request=$request status=$status '
                  'request_time=$request_time upstream=$upstream_addr '
                  'upstream_connect=$upstream_connect_time '
                  'upstream_header=$upstream_header_time '
                  'upstream_response=$upstream_response_time';
access_log /var/log/nginx/example-routed.log routed;

$request_time measures total request handling time. The upstream variables show whether Nginx connected to a backend, waited for response headers, or received a delayed response. A blank upstream value generally means the request did not reach a proxy upstream; check the selected block, static handling, redirects, or an early client/TLS failure.

Step 7: Increase debug detail only for the affected host

When normal logs do not reveal the decision, temporarily raise the error-log level to debug. The Nginx binary must support debug logging, and debug output can be extremely verbose.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
server {
    listen 80;
    server_name example.com;
    error_log /var/log/nginx/example-debug.log debug;
}

Reproduce one or two requests, collect the relevant lines, and restore the previous level. Keeping debug logging enabled on a busy production site can consume disk and obscure other events. A server-level debug log is useful because it isolates the virtual host instead of mixing every site’s traffic.

Step 8: Separate routing from reverse-proxy health

Once logs prove that the intended block handled the request, inspect the upstream path. Typical evidence is an upstream address in the access log, a connection error in the error log, or a large gap between upstream_connect_time and upstream_header_time.

Interpret common proxy symptoms

Observed result What it usually indicates Next check
Default page or another site’s HTML Wrong listener, unmatched name, or unintended default server Compare address family, Host value, and loaded listen/server_name map
Connection refused or immediate 502 Upstream port is closed, service is down, or the address is wrong Test backend reachability from the Nginx host and inspect service listening sockets
504 or long header wait Backend accepted the connection but did not produce headers in time Check application latency, dependency calls, and timeout settings
Some requests succeed after others fail One upstream member is unhealthy or retries are changing the selected member Inspect $upstream_addr, error logs, and upstream failure counters
Failures stop after a delay A passive health rule temporarily marked a failing upstream unavailable Review max_fails, fail_timeout, and the backend’s recovery pattern

Understand retries and passive health

Nginx can try another upstream after specified communication errors. That can hide a failing member in a browser while monitoring still sees elevated latency or occasional errors. Passive health checks infer failure from live requests; they are not a substitute for checking the service directly. Avoid increasing timeouts or retry counts until you know whether the problem is connection failure, header delay, or application response time.

Step 9: Validate and reload safely

  1. Save a copy of the currently deployed configuration and record the baseline access and error logs.
  2. Make one focused change, such as adding the missing IPv6 listener or correcting an alias.
  3. Run the deployed binary’s configuration test, for example nginx -t. Do not reload after a failed test.
  4. Reload through the service manager or the approved deployment mechanism so workers inherit the validated configuration.
  5. Repeat the same IPv4, IPv6, HTTP, HTTPS, alias, and unknown-host requests used before the change.
  6. Compare selected status codes, response bodies, certificates, upstream addresses, and timing fields in the before-and-after logs.

A reload changes future workers; existing connections may finish under the previous worker. Allow those connections to drain before judging a long-lived proxy or WebSocket test.

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

Choosing the right fix

Fix approach Best when Trade-off or risk
Add matching IPv4 and IPv6 listeners A dual-stack hostname reaches different behavior by address family Requires working IPv6 routing, firewall rules, certificates, and monitoring
List exact names and aliases Known hostnames are landing in a wildcard or default block Every new alias must be added and deployed deliberately
Use an explicit default server Unmatched or missing Host requests expose the first listed site Only one default can exist per socket; duplicate declarations fail validation
Narrow wildcard or regex rules Overlapping patterns capture traffic unexpectedly More explicit configuration is less convenient for large dynamic name sets
Align port 80 and 443 blocks Redirects, SNI, or certificates differ between HTTP and HTTPS Certificate renewal and redirect changes must cover both address families
Repair or remove an unhealthy upstream Routing is correct but backend errors are intermittent Changing retries alone can mask the underlying application or network fault

A compact troubleshooting checklist

  • Did you inspect the fully rendered configuration with includes expanded?
  • Does the intended block listen on every required address family and port?
  • Is the desired fallback explicitly marked default_server for each socket?
  • Does server_name include the exact hostname, aliases, and redirect destination?
  • Have you tested every A and AAAA address while preserving the intended Host and SNI values?
  • Do access logs identify the request and show whether an upstream was contacted?
  • Do error logs show connection failures, retries, or passive-health events?
  • Did you test with the same protocol, hostname, and port that the failing client uses?
  • Did nginx -t pass before the reload?
  • Did the post-reload tests produce the same expected result on IPv4 and IPv6?

Bottom line

Intermittent Nginx server-block behavior is usually a deterministic mismatch in address, port, hostname, TLS SNI, or default-server selection—not random routing. Render the active configuration, test each address family with the real hostname, make listeners and defaults explicit, and use access, error, and upstream timing logs to prove where a request went. Only after the correct block is confirmed should you tune or repair the reverse proxy and its upstream health.

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 *

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
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

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.