Bad Gateway Error Code 502 Cloudflare | Quick Fix Steps

Cloudflare 502 bad gateway means Cloudflare reached your site but got an invalid or no response from the origin server.

What This Error Means In Plain Terms

Quick read: A 502 bad gateway is an HTTP status from a gateway or proxy that tried to fetch your page from another server and got a bad reply. With Cloudflare in front, your browser hits Cloudflare first, and Cloudflare asks your origin for the page. If that upstream reply is invalid or missing, you see the message. MDN states that a 502 appears when a gateway receives an invalid response from the upstream server, which fits this pattern for Cloudflare users.

In Cloudflare’s docs, 502 can come from two places: the origin web server (most common) or Cloudflare’s edge during rare routing or protocol hiccups. Your first job is to tell which side produced the page so you can pick the right fix now.

Bad Gateway Error Code 502 Cloudflare — Causes And Fixes

Goal: Split the problem into origin issues and Cloudflare edge issues, then apply the matching fix. This saves time and avoids blind guesses.

Origin Web Server Issues (Most Common)

  • Server overload or crash — Traffic spikes, memory limits, or a database hang leave PHP-FPM, Node, or the app unresponsive.
  • Process manager trouble — PHP-FPM workers or app processes die or hit limits, so Nginx returns bad gateway to Cloudflare.
  • Upstream timeouts — Long queries or slow APIs exceed timeouts and the upstream closes or replies late.
  • Bad compression or headers — The origin serves broken gzip or a wrong content-length; Cloudflare flags the response as invalid.
  • Firewall blocks Cloudflare — Host, iptables, or a WAF denies Cloudflare IP ranges, so Cloudflare can’t fetch the page.
  • Wrong DNS target — The A/AAAA in Cloudflare points at an old or wrong origin IP, so the request lands on a server that can’t serve the host.
  • SSL/TLS mismatch — Cipher or certificate problems between Cloudflare and origin break the handshake.

Cloudflare Edge Or Network Glitches

  • Temporary edge routing shift — A busy data center can reroute traffic for a short period; some clients may see brief 502s.
  • Gateway protocol quirks — Partially supported HTTP/2 at the origin or broken gzip triggers a 502 generated by Cloudflare.

Cloudflare 502 Bad Gateway: Fast Causes And Fixes

Start here: Match the page you see to the source. A Cloudflare-branded 502 usually mirrors an origin 502. A plain, unbranded 502 points to Cloudflare generating the error. That single clue decides your next step.

What You See Likely Source Next Step
Cloudflare-branded 502 page Origin returned 502/504 Inspect app, logs, and host health
Blank 502 page without branding Generated by Cloudflare Test compression/protocols; check Cloudflare status
Ray ID on the page Use it to trace request Share timestamp, URL, and /cdn-cgi/trace with the team

Quick Checks For Site Owners And Visitors

For visitors: Refresh once, then try another browser or a cellular network. If the site loads elsewhere, the issue sits on the path or your browser. If it fails everywhere, the site likely has an origin problem.

  • Reload the page — A single retry can work if the error was a short surge.
  • Try a different network — Switch Wi-Fi to mobile data to rule out a local path quirk.
  • Clear the cache — Purge browser cache and cookies for the site, then test again.

For site owners: These quick actions often separate symptom from cause within minutes.

  • Bypass Cloudflare — Temporarily grey-cloud the DNS record or test the origin by IP/host file to see the raw origin response.
  • Check host status — Look at CPU, memory, PHP-FPM workers, database status, and error logs.
  • Confirm DNS target — The A/AAAA in Cloudflare should match the live origin IP at your host.
  • Allow Cloudflare IPs — Ensure your firewall and security tools allow Cloudflare IP ranges.
  • Disable broken gzip — Turn off compression on the origin and retest if pages 502 on large or dynamic content.
  • Toggle HTTP/2 to origin — If your stack partly speaks HTTP/2, test with HTTP/1.1 to rule out protocol bugs.

Proof-Driven Diagnostics That Save Hours

Capture the trail: Open DevTools, record a HAR, and note the exact time and URL. Load /cdn-cgi/trace on your domain and save the output. Those items plus your Ray ID form a complete report.

  • Hit the origin directly — Use curl -I http://ORIGIN_IP with the Host header set to your domain. If the origin returns 200/301, the app is alive.
  • Compare status codes — In Cloudflare Analytics, check Edge Status Code vs Origin Status Code to learn where the 5xx started.
  • Read web server logs — Look for upstream timed out, bad gateway, handshake failure, or worker limits reached.
  • Check TLS mode — Pick the right SSL/TLS mode. Full (strict) with a valid cert at origin is the safer baseline.
  • Retry with features off — Temporarily pause features like Early Hints or HTTP/2 to isolate a protocol or cache quirk.
Symptom Likely Cause Where To Fix
502 only on heavy pages Compression or header mismatch Origin web server settings
502 on peaks Process or DB saturation Scale workers, tune DB, add cache
Ray ID shows same DC Edge reroute moment Wait a minute, then re-test
Works direct, fails via CF Firewall blocking CF IPs Allow Cloudflare IP ranges
Only with HTTP/2 to origin Partial HTTP/2 support Force HTTP/1.1 while you patch

Setting Changes That Fix The Root Cause

SSL/TLS mode: Use Full (strict) with a valid certificate at the origin. If you use Origin CA, keep Cloudflare proxy on for hostnames that present that cert. Reissue if the cert expired or the hostnames changed.

  • Raise app headroom — Increase PHP-FPM workers or Node pool size within safe memory limits.
  • Tune timeouts — Set upstream/read timeouts to match real query time, then shave heavy queries.
  • Fix DNS drift — Update A/AAAA records in Cloudflare when your host assigns a new origin IP.
  • Match protocols — If the origin struggles with HTTP/2, pin to HTTP/1.1 until the stack is updated.
  • Sanity-check gzip — Disable broken compression or correct content-length behavior.
  • Open the door for Cloudflare — Allow the published Cloudflare IP ranges in your host firewall and security rules.

Prevent 502s With Monitoring And Good Hygiene

Watch the scoreboard: Set an Origin Error Rate alert in Cloudflare, then pair it with host metrics on CPU, memory, queue length, and DB waits. That pairing spots overload conditions before the site trips.

  • Add health checks — If you use a load balancer, monitor per-pool latency and mark down bad nodes fast.
  • Cache the heavy parts — Use page rules or cache rules for stable routes; ship stale-while-revalidate where it fits.
  • Profile slow queries — Reduce long-running DB work that keeps upstreams busy.
  • Set keepalives — Enable and tune keepalive on origin servers to reuse connections.
  • Document failover — Keep a runbook: where logs live, how to toggle grey-cloud, which features to pause first.

Step-By-Step Fix Flow You Can Use Under Pressure

  1. Verify the scope — Test one static page, one dynamic page, and your homepage. Note which paths fail.
  2. Snapshot the moment — Copy the Ray ID, exact URL, and local time with timezone. Start a plain-text incident note.
  3. Record a HAR — Use a private window, hit the failing URL, export the HAR. Attach it to your ticket.
  4. Try the origin directly — Use curl -svo /dev/null https://ORIGIN_IP with -H "Host: yourdomain.com". Save the status and any TLS errors.
  5. Grey-cloud a test route — Switch one DNS record to DNS-only and retest that path. If it loads, focus on the Cloudflare side.
  6. Check recent changes — New deploy, plugin, theme, or server patch? Roll back the last change and retest.
  7. Read origin logs — Search for phrases such as “upstream timed out”, “bad gateway”, “header too large”, or “handshake failure”.
  8. Inspect process health — Confirm PHP-FPM workers, Node processes, or application pods are running and accepting connections.
  9. Confirm firewall rules — Make sure Cloudflare IP ranges are allowed and not rate limited on the host.
  10. Test without compression — Disable gzip or brotli at the origin and retry heavy pages.
  11. Switch protocol for origin — If you suspect HTTP/2 issues, force HTTP/1.1 between Cloudflare and your origin, then re-enable once fixed.

Notes For Common Stacks

Nginx + PHP-FPM

Triage: Look for upstream timed out, no live upstreams, or connect() failed in the error log. Raise pm.max_children, ensure fastcgi_read_timeout matches real page work, and keep DB queries short.

Node And Reverse Proxies

Triage: Check process restarts and memory ceilings. Keep a small worker pool behind Nginx and raise keepalive. If a long upstream call blocks the event loop, push it to a worker thread or queue.

WordPress And Similar CMS

Triage: Disable new plugins, purge all cache layers, and test with a default theme. Page builders can stress PHP-FPM; profile slow routes and cache HTML where safe.

Why Some 502s Vanish On Their Own

Edge routing can shift traffic away from a busy data center for a short window. During that shift, a few clients can see brief 502 responses. The redirection completes quickly, and the site resumes. If the error clears on a single refresh and doesn’t return, you can log the event and move on, then check analytics for a blip.

What To Send If You Need Cloudflare Help

Make your ticket actionable: Include the Ray ID, URL, precise timestamp with timezone, your /cdn-cgi/trace output, and a link to a HAR file. State whether the error page was branded or blank. Add what you learned from testing the origin directly. With that, an engineer can match logs and confirm where the failure started now.

Where The Evidence Comes From

This guidance aligns with Cloudflare’s 502/504 documentation, which explains that branded 502 pages mirror origin errors while blank 502 pages can be generated by Cloudflare, often tied to compression or protocol quirks and rare routing shifts. MDN’s reference defines 502 as a gateway receiving an invalid upstream response. Cloudflare’s troubleshooting notes also show how to gather a HAR, share the exact timestamp, and include /cdn-cgi/trace when opening a ticket, and the analytics view that compares edge and origin status codes so you can see where a 5xx started.

Use the phrase bad gateway error code 502 cloudflare when you write incident notes so your team can quickly find them later; repeat bad gateway error code 502 cloudflare in your host ticket to keep the scope clear.

References