The bad gateway error 502 means a gateway or proxy got an invalid response from an upstream server in the request chain.
Seeing “502” on a page usually means a server in the middle — a load balancer, CDN, reverse proxy, or web server acting as a gateway — talked to another server and got a bad reply. You can clear it as a visitor with a few quick checks, and you can fix it as a site owner by tracing the hop that failed and tightening configs that commonly break under load.
Bad Gateway Error 502
Quick context: In HTTP, 5xx codes signal server-side problems. A “502 bad gateway” occurs when a gateway or proxy did reach an upstream server but the reply was invalid or incomplete. If no reply arrived in time, a 504 would be sent instead; if the origin is overloaded or down for maintenance, a 503 often fits better. Knowing these differences helps you aim your fix where it matters.
What Users Typically See
- Generic page text — A white page with “502 Bad Gateway” or “Bad Gateway” from the server.
- Vendor-flavored pages — A branded error from a CDN or proxy such as a Cloudflare “502 Bad Gateway” screen.
- IIS subcodes — Variants like
HTTP Error 502.3hint at a timeout or a proxy handoff problem.
Fast Visitor Checks That Often Clear A Temporary 502
These steps help confirm whether the issue is on your device or on the site’s side. Try them in order; stop once the page loads.
- Refresh The Page — Hit reload or press Ctrl/⌘+R. Short spikes can trigger a stale 502 that clears on retry.
- Open A New Tab — Paste the same URL in a fresh tab or window to bypass a stuck tab process.
- Try Another Browser — If it loads in a second browser, reset or reinstall the first one.
- Disable VPN/Proxy — Turn off your VPN or custom proxy profile and retry the page.
- Clear Cache And Cookies — Remove site data for the domain; stale cookies can trip upstream auth or header limits.
- Flush DNS Or Change Resolver — Switch to a public resolver (1.1.1.1 or 8.8.8.8) and retry.
- Check The Site’s Status — If the site or service has a status page or social feed, a current incident may already be posted.
Fixing 502 Bad Gateway On Nginx: Practical Steps
Goal: prove where the chain breaks, fix the upstream, and right-size proxy settings. The items below assume a reverse proxy such as Nginx in front of an app (PHP-FPM, Node, Python, Ruby) or a second web server.
Verify Upstream Health
- Hit The Upstream Directly — From the proxy host,
curl -I http://upstream:port/health. A clean 200/204 proves the app responds. - Check Process Pool — Ensure PHP-FPM workers, Node processes, or Gunicorn/Unicorn workers are running and have headroom.
- Scan Error Logs — Read both sides:
/var/log/nginx/error.logand the app/server log for stack traces, crashes, or OOM kills.
Fix Common Nginx ↔ Upstream Breaks
- Address Connection Refused — Mismatch between
fastcgi_pass/proxy_passand the actual upstream socket or port. Align the socket path or port, and open firewall rules as needed. - Raise Timeouts For Slow App Paths — Tune
proxy_read_timeout,proxy_connect_timeout, andfastcgi_read_timeoutfor long-running endpoints such as large reports or cold cache fills. - Handle “Upstream Sent Too Big Header” — Increase header buffers when SSO or cookies get bulky:
proxy_buffer_size 16k; proxy_buffers 8 16k; proxy_busy_buffers_size 24k; - Right-Size Body Limits — If uploads trigger a 502 via upstream resets, raise
client_max_body_sizeand ensure the app accepts that size. - Stabilize PHP-FPM Pools — For bursts that exhaust workers, raise
pm.max_children, allow short queues (pm.max_spare_servers), and watch memory pressure. - Fix DNS Drift — If the proxy resolves the upstream by name, point Nginx to a reliable resolver and consider IPs or local DNS pinning for critical paths.
- Clean TLS Handshakes — When proxying HTTPS upstreams, confirm CA trust, SNI, and protocol/cipher compatibility with
openssl s_client.
Log What Matters During A Spike
- Enable Request IDs — Add a request ID header and echo it end-to-end so you can correlate logs across layers.
- Sample 5xx With Details — Use a dedicated
error_page 502location to log upstream status, time to first byte, and server name. - Capture Upstream Timing — Log
$upstream_statusand$upstream_response_timein your access log format.
Cloudflare 502 Variants And What They Mean
When a site sits behind Cloudflare, a “502” can originate at the edge or at the origin. The page wording helps you pinpoint the side to fix.
- “Bad Gateway” At The Edge — Cloudflare reached the origin but got an invalid reply. Inspect origin logs, firewall, and app health.
- “Host Error” — The origin failed outright or closed the connection mid-stream. Check origin capacity, TLS, and upstream timeouts.
- Quick tests — Bypass the proxy (gray-cloud DNS record temporarily), hit the origin directly from a safe IP, and compare results to confirm the fault domain.
Admin Playbook: Confirm, Compare, Repair
Use a short loop to move from guesswork to proof. This works for Nginx, Apache, or a managed proxy.
- Confirm The Layer — Check the error page source and logs. A CDN-branded page points to the edge; a plain server page points to your proxy or app.
- Compare Paths — If static files load but dynamic pages fail, check app workers and database connections.
- Replay With cURL — Run the request from the proxy host. Add
-vto see header flow and TLS hints. - Kill The Bottleneck — Raise timeouts, fix the upstream address, or add app capacity. Re-test under load.
- Watch For Regression — Keep a dashboard on 5xx rate, upstream time, and worker usage.
“502 Bad Gateway” Vs. 504 And 503: What’s Different
- 502 Bad Gateway — A gateway got an invalid reply from an upstream server.
- 504 Gateway Timeout — A gateway waited for a reply and none arrived in time.
- 503 Service Unavailable — The origin is overloaded or down for planned work; a
Retry-Afterheader may be present.
Tip: If a path succeeds on retry with a short delay, 504 or 502 due to slow backends is likely. If it fails instantly and the error page never changes, check routing, TLS, and header limits first.
Common Causes And Fixes (At A Glance)
| Cause | Symptom | Quick Fix |
|---|---|---|
| Pool Exhausted (PHP-FPM/Workers) | Spikes return 502 on dynamic routes; static files OK | Raise worker count, add autoscaling, cache hot responses |
| Header Too Large | 502 after SSO/login; big cookies present | Increase proxy header buffers; trim cookies and headers |
| Proxy Timeout Too Low | Long tasks fail near the same duration | Raise read/connect/send timeouts; add background jobs |
| Wrong Upstream Address | Instant 502; connection refused in logs |
Fix proxy_pass/fastcgi_pass and firewall rules |
| DNS Resolution Drift | Fails after deploy or TTL expiry | Pin upstream IPs or set stable internal DNS/resolver |
| TLS Mismatch To Origin | 502 on HTTPS upstream only | Trust the origin CA, enable SNI, align protocols/ciphers |
| CDN “Host Error” | 502 only through the CDN | Bypass the CDN to test; fix origin capacity or firewall |
Prevention Checklist For Site Owners
- Set Health Checks — Gate traffic with load-balancer probes and mark failed targets out of rotation quickly.
- Cache Smartly — Put CDN or proxy caching on public assets and safe API responses to reduce app load.
- Right-Size Buffers — Keep proxy header and body buffers large enough for SSO and modern cookies.
- Tune Timeouts Per Route — Fast pages can keep short timeouts; report or export routes need longer windows.
- Scale On Metrics — Trigger extra workers on queue depth, CPU, or response time, not only on raw traffic.
- Trim Cookies — Keep cookie size in check; move bulky state to server-side storage.
- Record Request IDs — Propagate a unique ID from edge to app to trace 5xx across layers.
- Document Runbooks — Save the timeout, buffer, and pool settings that cleared past incidents.
When To Escalate
As a visitor: if multiple sites load except one, the site’s team needs to fix it. Share the time, your region, and a screenshot of the error page.
As a site owner: escalate when 5xx rates spike or when 502s cluster on a single path. Provide request IDs, upstream IPs, and timings so hosting, CDN, or database teams can act quickly.
Bad Gateway Error 502: Clear, Fix, And Prevent
The bad gateway error 502 doesn’t have to be a mystery. Visitors can retry, switch networks, or clear local state. Admins can prove the fault domain with a direct cURL test, fix upstream address and pool issues, raise timeouts where needed, and keep buffers and cookies sized for modern auth flows. With baseline health checks, caching, and observability, the same conditions that once caused a 502 turn into a short blip instead of a long outage.
