What 502 Bad Gateway means

502 Bad Gateway means the proxy or load balancer sitting in front of the actual server received a malformed or unexpected response from upstream. Classic causes: upstream crashed mid-response, upstream returned protocol garbage, connection was reset before the response completed. 502 is one of the most common error codes from CDNs (Cloudflare, AWS CloudFront, Fastly) and reverse proxies (Nginx, HAProxy).

When servers should return it: A proxy or CDN returns 502 when it cannot get a valid response from the origin. Origin operators see this as "the proxy is reporting we returned garbage".

Common causes

  • Origin server crashed mid-request
  • Origin returned non-HTTP response (raw error text, wrong port)
  • Connection reset by origin
  • Origin SSL certificate invalid or expired
  • Origin closed the connection before sending the full response
  • Upstream timeout (sometimes manifests as 502 instead of 504)

How to fix 502 Bad Gateway

  • Check origin server logs for crashes or errors
  • Verify origin is actually running and reachable on the right port
  • Check origin certificate validity
  • For Cloudflare 502s, check the Cloudflare event log and origin response
  • Retry the request, often transient

Example response

HTTP/2 502
server: cloudflare
content-type: text/html
<html><body>502 Bad Gateway</body></html>

More references

For a one-page reference of all HTTP status codes, see the HTTP cheat sheet. For testing API responses, try the API Tester tool. For inspecting responses on the command line, the curl cheat sheet covers the most common flags.