WhichWebHosting home

HomeGuidesError fixesHow to fix a 502 Bad Gateway error

How to fix a 502 Bad Gateway error

Published

Share

A 502 Bad Gateway error means a server acting as a gateway or proxy received an invalid response from the server behind it.1, source 1 Fixing this error probably requires investigation by the server owners or administrators.2, source 2 The exceptions are networking errors on the visitor's side, particularly with VPNs or other custom networking setups.2, source 2

What does a 502 Bad Gateway error mean?

The HTTP 502 Bad Gateway server error response status code indicates that a server was acting as a gateway or proxy and received an invalid response from the upstream server.2, source 2 A gateway, also called a reverse proxy, is an intermediary that acts as an origin server for the outbound connection but translates received requests and forwards them inbound to another server or servers.1, source 1 A 502 response is similar to a 500 Internal Server Error in that it is a generic catch-all for server errors.2, source 2 What sets a 502 apart from a 500 is that it is specific to the point in the request chain where the error occurred.2, source 2

A 500 (Internal Server Error) status code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.1, source 1 The 5xx (Server Error) class of status codes indicates that the server is aware that it has erred or is incapable of performing the requested method.1, source 1 Except when responding to a HEAD request, a server should send a representation containing an explanation of the error situation and whether it is a temporary or permanent condition.1, source 1 When the origin server sends a valid HTTP error response to the gateway, the response should be passed on to the client instead of a 502, so the reason for the failure is transparent.2, source 2

When the proxy or gateway did not receive any HTTP response from the origin, it sends a 504 Gateway Timeout to the client instead of a 502.2, source 2 A 504 (Gateway Timeout) status code indicates that a server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access to complete the request.1, source 1 A 503 (Service Unavailable) status code indicates that the server is unable to handle the request due to a temporary overload or scheduled maintenance.1, source 1

What causes a 502 Bad Gateway error?

There are many causes of 502 errors.2, source 2 Cloudflare names two possible causes of 502 and 504 errors: the origin web server, which is the most common, and Cloudflare itself.3, source 3 When a site is behind Cloudflare, an HTTP 502 or 504 error indicates that Cloudflare is unable to establish contact with the origin web server.3, source 3 Causes to check at the origin web server include excessive server loads, crashes, or network failures.3, source 3

Another origin-side check is to identify applications or services that timed out or were blocked.3, source 3 The cause of a 5xx error is not always found in the origin server's error logs, so the logs of any load balancers, caches, proxies, or firewalls between Cloudflare and the origin web server also need checking.4, source 4 While Cloudflare's automated processes redirect traffic to another data center, some clients may experience temporary latency or HTTP 502 errors.3, source 3 Through Cloudflare Tunnel, a 502 Bad Gateway error with the message Unable to reach the origin service means the tunnel itself is connected to the Cloudflare network but cloudflared cannot reach the origin service defined in the ingress rule.5, source 5

What can you check first?

Cloudflare Support only assists the domain owner, so a site visitor should report the problem to the site owner.4, source 4 Behind Cloudflare, the correct first step for most 5XX errors is to contact your hosting provider or site administrator to troubleshoot and gather data.4, source 4

Cloudflare Support asks for the output from browsing to <YOUR_DOMAIN>/cdn-cgi/trace when you report a 502 or 504.3, source 3 A HAR file, often the first thing Cloudflare Support will request, records all web browser requests, including the request and response headers, the body content, and the page load time.6, source 6 When generating a HAR file, use Incognito Mode or a Private Browsing window.6, source 6 A HAR file can include sensitive details such as passwords, payment information, and private keys, so remove sensitive information with a HAR sanitizer.6, source 6

Initial diagnostic steps

  1. Check network settings, firewall setup, proxy settings, DNS configuration, and similar settings when the service works for other visitors and clients use VPNs or other custom networking setups.2, source 2
  2. When contacting a hosting provider about a 5XX error, share the specific 5XX error code and message.4, source 4
  3. Share the time and timezone when the error occurred.4, source 4
  4. Share the URL that resulted in the error.4, source 4

How do you find where the 502 comes from?

To resolve 502 or 504 errors behind Cloudflare, it is essential to identify whether the issue originates from the origin web server or from Cloudflare.3, source 3 When the error page is Cloudflare-branded, the 502 or 504 came from the origin web server, so contact your hosting provider.3, source 3 A 502 or 504 error that originates from Cloudflare appears as a blank page without the Cloudflare branding.3, source 3

The Ray ID identifies one request within a connection, and sending it with a packet capture lets Cloudflare Support match the frames in the capture to the request that was slow or failed.6, source 6 Each request's Ray ID is in the cf-ray response header, and on a Cloudflare error page it also appears at the bottom.6, source 6 When you log the CF-RAY header at your origin, you can take the Ray ID from your logs instead.6, source 6

Cloudflare's error analytics per domain are available within Zone Analytics and break down errors by HTTP error code.4, source 4 To view error analytics in the Cloudflare dashboard, go to the HTTP Traffic page, select Add filter, choose Edge status code or Origin status code, and pick the 5xx error code to diagnose.4, source 4

On a WordPress site, setting WP_DEBUG_LOG to true saves errors to a debug.log file in the content directory, usually wp-content/debug.log.7, source 7 For WP_DEBUG_LOG to do anything in WordPress, WP_DEBUG must be enabled.7, source 7 In WordPress, setting WP_DEBUG_DISPLAY to false hides debug messages in the page HTML, and it should be used with WP_DEBUG_LOG so errors can be reviewed later.7, source 7 WordPress does not recommend using WP_DEBUG or its other debug tools on live sites, because they are meant for local testing and staging installs.7, source 7

WordPress advises using a staging environment or taking a backup of the site before making any modifications.7, source 7

Steps to isolate the source

  1. To test whether the origin caused an HTTP error, send requests directly to the origin web server's IP address, bypassing Cloudflare's proxy.6, source 6
  2. Run Cloudflare's example command for testing the origin directly: curl -svo /dev/null http://example.com --connect-to ::203.0.113.34, where the last value is the origin's IP address.6, source 6
  3. Contact your hosting provider for assistance when the issue also appears when connecting directly to the origin web server.6, source 6
  4. Alternatively, pause Cloudflare to route traffic directly to the origin, bypassing Cloudflare's proxy, which helps determine whether an issue is caused by Cloudflare or the origin server.6, source 6

How do you fix a 502 on nginx and PHP-FPM?

The nginx ngx_http_proxy_module allows passing requests to another server.8, source 8 Its proxy_pass directive sets the protocol and address of a proxied server, and the protocol can be http or https.8, source 8

The nginx proxy_next_upstream directive specifies in which cases a request should be passed to the next server, and its error parameter covers an error while establishing a connection with the server, passing a request to it, or reading the response header.8, source 8 Its invalid_header parameter covers a server returning an empty or invalid response, and its http_502 parameter covers a server returning a response with the code 502.8, source 8 The http_500, http_502, http_503, http_504 and http_429 cases count as unsuccessful attempts only when they are specified in proxy_next_upstream.8, source 8 Passing a request to the next server is only possible when nothing has been sent to the client yet.8, source 8

In nginx, max_fails sets the number of unsuccessful attempts within the fail_timeout period after which a server is considered unavailable, and the default is 1.9, source 9 The fail_timeout parameter sets both the window for counting unsuccessful attempts and how long a server is then considered unavailable, and its default is 10 seconds.9, source 9 When there is only a single server in a group, the max_fails, fail_timeout and slow_start parameters are ignored and that server is never considered unavailable.9, source 9

The nginx ngx_http_fastcgi_module allows passing requests to a FastCGI server.10, source 10 Its fastcgi_pass directive sets the address of a FastCGI server, either a domain name or IP address with a port, or a UNIX-domain socket path.10, source 10 The first part of a FastCGI response usually contains a small response header, and when it exceeds the fastcgi_buffer_size buffer, the response is considered invalid.10, source 10 The nginx fastcgi_catch_stderr directive sets a string to search for in the error stream of a FastCGI response, and when the string is found the FastCGI server is considered to have returned an invalid response.10, source 10

In PHP-FPM, the listen directive sets the address on which to accept FastCGI requests, and it is mandatory for each pool.11, source 11 When the web server runs on the same host as PHP-FPM, a Unix socket should be preferred.11, source 11 The PHP-FPM pm setting controls how the process manager sets the number of child processes, and the possible values are static, ondemand and dynamic.11, source 11 With pm set to ondemand, PHP-FPM child processes spawn on demand, and idle processes are killed after pm.process_idle_timeout.11, source 11

The PHP-FPM request_terminate_timeout is the timeout for serving a single request after which the worker process is killed, to be used when the max_execution_time ini option does not stop script execution for some reason, and a value of 0 means Off.11, source 11 With PHP-FPM request_slowlog_timeout, a PHP backtrace is dumped to the slowlog file once a single request exceeds the timeout, and 0 means Off.11, source 11 The PHP-FPM error_log directive sets the path to the error log file, and when it is set to syslog the log is sent to syslogd instead of a local file.11, source 11

Settings to check in nginx and PHP-FPM

  1. Check the nginx proxy_connect_timeout directive, which defines a timeout for establishing a connection with a proxied server, and its default is 60s.8, source 8
  2. Check the nginx proxy_read_timeout directive, which defines a timeout for reading a response from the proxied server, and its default is 60s; the timeout is set only between two successive read operations, not for the transmission of the whole response.8, source 8
  3. Check the nginx proxy_send_timeout directive, which sets a timeout for transmitting a request to the proxied server, and its default is 60s.8, source 8
  4. Check the nginx proxy_next_upstream directive, whose default is error timeout.8, source 8
  5. Check the nginx fastcgi_connect_timeout directive, which defines a timeout for establishing a connection with a FastCGI server, and its default is 60s.10, source 10
  6. Check the nginx fastcgi_read_timeout directive, which defines a timeout for reading a response from the FastCGI server, and its default is 60s.10, source 10
  7. Check the PHP-FPM pm.max_children setting, which sets the limit on the number of simultaneous requests that will be served.11, source 11

How do you fix a 502 on Apache?

With ProxyBadHeader set to IsError, Apache's mod_proxy aborts the request when it receives bad header lines from the backend and returns a 502 (Bad Gateway) response.12, source 12 With Ignore, mod_proxy treats bad header lines as if they were not sent.12, source 12 The StartBody setting of ProxyBadHeader helps work around buggy backend servers that forget to insert an empty line between the headers and the body.12, source 12

ProxyTimeout is useful for a slow or buggy application server that hangs, so Apache returns a timeout and fails gracefully instead of waiting however long the server takes.12, source 12 Apache's example ProxyPass line with timeouts is ProxyPass "/example" "http://backend.example.com" connectiontimeout=5 timeout=30.12, source 12

The Apache ProxyPass disablereuse parameter forces mod_proxy to close a connection to the backend immediately after use, which disables its persistent connection and pool for that backend.12, source 12 Disabling connection reuse helps where a firewall between Apache httpd and the backend server tends to silently drop connections.12, source 12 In Apache, when the connection pool worker to the backend server is in the error state, Apache does not forward any requests to that server until the retry timeout expires.12, source 12

Apache's ProxyErrorOverride overrides error pages for proxied content, and its default is Off.12, source 12 Set to On with no status codes listed, it affects all responses with codes from 400 up to but not including 600.12, source 12 In Apache 2.4.47 and later, ProxyErrorOverride can be given a list of status codes, such as ProxyErrorOverride On 403 405 500 501 502 503 504.12, source 12

Settings to check in Apache

  1. Check the Apache ProxyBadHeader setting, whose default is IsError.12, source 12
  2. Check the Apache ProxyTimeout directive, which sets a network timeout for proxied requests, and its default is the value of Timeout.12, source 12
  3. Check the Apache ProxyPass connectiontimeout parameter, which is the number of seconds Apache waits for the creation of a connection to the backend to complete.12, source 12
  4. Check the Apache ProxyPass timeout parameter, which is the socket timeout, the number of seconds Apache waits for data sent by or to the backend.12, source 12

How do you fix a 502 behind Cloudflare or a tunnel?

An unbranded 502 or 504 from Cloudflare can occur due to a compression issue at the origin, such as the origin serving gzip-encoded content without updating the content-length header, or the origin serving broken gzip compressed content.3, source 3 To diagnose an unbranded 502 or 504 caused by compression, try disabling compression at the origin to confirm whether that resolves the error.3, source 3 Cloudflare says that using Gateway can lead to an HTTP 502 error when the origin only partially supports HTTP/2.3, source 3

When you use Dedicated CDN Egress IPs to connect to your origin, a 502 error can occur when Cloudflare temporarily runs out of available source ports while opening new connections to your origin.3, source 3 When you suspect Dedicated CDN Egress IP port exhaustion, contact your account team to review your Dedicated CDN Egress IPs capacity and placement.3, source 3

Unlike error 1033, which indicates the tunnel is not connected to Cloudflare, a Cloudflare Tunnel 502 error indicates the problem is between cloudflared and your local service.5, source 5 To identify the specific cause of a Cloudflare Tunnel 502, review your Tunnel logs for error-level messages.5, source 5

When the origin service behind a tunnel has stopped or never started, cloudflared logs show an error such as dial tcp [::1]:8080: connect: connection refused.5, source 5 You can confirm a service is listening by running ss -tlnp | grep <PORT> on Linux or lsof -iTCP -sTCP:LISTEN -nP | grep <PORT> on macOS.5, source 5 When the origin expects HTTPS but the tunnel route specifies http://, or the reverse, cloudflared logs show a malformed HTTP response error.5, source 5 When the port in the tunnel route does not match the port the service is listening on, cloudflared logs a connection refused error for that port.5, source 5

When the origin presents a TLS certificate that cloudflared cannot verify, an error such as x509: certificate is valid for example.com, not localhost indicates the certificate does not cover the service hostname.5, source 5 To fix the certificate problem, set originServerName to the hostname on the origin certificate in the tunnel route, or provide the CA certificate to cloudflared using caPool.5, source 5 Disabling TLS verification with noTLSVerify is a temporary last resort, and noTLSVerify should be turned off after the certificate issue is resolved.5, source 5

Checks for a Cloudflare Tunnel

  1. To resolve a stopped origin service behind a tunnel, verify the service is running and listening on the expected port, for example with curl -v http://localhost:8080.5, source 5
  2. To resolve a protocol mismatch, update the service URL in your tunnel route to match the protocol your origin expects.5, source 5

Common questions

What does a 502 Bad Gateway error mean?

It means a gateway or proxy received an invalid response. The response came from the upstream server it accessed while trying to fulfill the request.

What causes a 502 Bad Gateway error?

Many issues can cause this error. Behind Cloudflare, causes to check at the origin web server include excessive server loads, crashes, or network failures. Fixing such problems probably requires investigation by server owners.

Is a 502 the same as a 504?

No. A 504 Gateway Timeout means the gateway or proxy did not receive any timely HTTP response from the upstream server, whereas a 502 means it received an invalid response.

Can I fix a 502 as a visitor?

Sometimes. The exceptions to needing a server owner are client networking errors, particularly when the service works for other visitors and clients use VPNs or other custom networking setups. In those cases, check your network settings, firewall setup, proxy settings and DNS configuration.

Where can I check for errors on a WordPress site?

In the debug log, once debug logging is on. With WP_DEBUG enabled, setting WP_DEBUG_LOG to true saves errors to debug.log in the content directory, usually wp-content/debug.log. WordPress does not recommend its debug tools on live sites, because they are meant for local testing and staging installs.

Sources

Every fact on this page comes from one of these, checked before it goes live.

More guides

Error fixes

What does HTTP error 404 (Not Found) mean?

An HTTP 404 error means the server cannot find the requested resource. Common causes are mistyped URLs and pages moved or deleted without a redirect.

· Mateo Cardenas

Email hosting

Does 123 Reg hosting include email?

123 Reg's Web Hosting, Hosting for WordPress and Premium Hosting plans include email addresses, and 123 Reg sells Titan and Microsoft 365 email plans.

· Mateo Cardenas

Email hosting

Does web hosting include business email?

Web hosting sometimes includes business email. See what SiteGround, Namecheap and HostGator state, then how MX records and SPF records work.

· Mateo Cardenas