Web

502 Bad Gateway Error: What It Means and How to Fix It

Talha Aslan 19 min read 3 views

What is a 502 Bad Gateway error?

A 502 Bad Gateway error is an HTTP status code. It means a server acting as a gateway or reverse proxy received an invalid response from the upstream server behind it. Your browser reached the site, but the front door could not get a proper answer from the application.

We are a digital marketing and web team, not a hosting company. The technical explanations here rest on MDN, RFC 9110, and the official nginx, PHP and Cloudflare documentation. Our goal is simple. When your site shows a 502, you should know where the error comes from and what to tell the right person.

In daily life, a 502 Bad Gateway error appears as "502 Bad Gateway", "Bad Gateway" or "HTTP Error 502". Sometimes a refresh fixes it. Sometimes it lasts for hours. This guide covers the causes, the diagnosis order and separate step lists for each role.

Who needs to fix a 502 error: the visitor, the site owner or the server admin?

In practice, the fix belongs on the server side in most cases. MDN describes this status as a server error that server owners and administrators should investigate. However, there is one exception. If the site works for other people and you use a VPN or a custom network setup, the problem may sit on your side.

You can split the roles like this:

  • Visitor: Reload the page, turn off the VPN, try another network and tell the site owner.
  • Site owner: Review the latest change, plugin, theme and CDN setting, then contact the host with the right details.
  • Server admin: Check the link between the reverse proxy and the app, the service status, the logs and the resource limits.

On shared hosting, the admin role belongs to your provider. So if you use cPanel without root access, the commands below are for your host, not for you.

How does a request travel between the reverse proxy and the upstream?

In practice, a request on a modern site rarely ends on one machine. The visitor first reaches a CDN or the web server itself. A front door such as nginx or Apache then hands the request to PHP-FPM, Node.js or another application server. That back layer is called the upstream.

In short, a 502 happens during this handoff. The front door works, but the upstream is down, refuses the connection, cuts it short or sends a reply nobody can read. As a result, the front door reports that it received an invalid response.

Think of the chain like this:

  1. The visitor sends a request from the browser.
  2. A CDN or reverse proxy receives it.
  3. The request goes to the application layer, such as PHP-FPM, Node.js or Python.
  4. Next, the application talks to a database or another service.
  5. Finally, the response travels back along the same path.

However, with several upstreams the picture changes a little. Then a load balancer or nginx spreads requests across servers that look healthy. According to the nginx documentation, the default for proxy_next_upstream passes a request to the next server on an error or a timeout. Still, if every upstream fails, the visitor sees a 502 or a similar error.

Finding the failing link is half of the fix.

What is the difference between 502, 500, 503 and 504?

All four are server-side errors, but they mean different things, so the details matter. RFC 9110 defines a 502 as a gateway receiving an invalid response from an inbound server. A 504 means the gateway got no timely response. Meanwhile, a 503 means the server cannot handle the request because of temporary overload or maintenance. A 500 is the generic server error.

We cover 500 and 503 in separate articles, so here we only summarize the difference.

CodeShort meaningFirst place to look
500The application hit an unexpected errorApplication and PHP error log
502The gateway got an invalid response from upstreamUpstream service, reverse proxy error log
503The server cannot serve for nowOverload, maintenance mode, resource limit
504The gateway did not get a timely responseSlow queries, timeout settings

MDN says a gateway sends a 504 when it receives no HTTP response at all. In practice, some stacks apply this split differently. So trust the sentence in the log, not just the code.

What are the most common causes of a 502 Bad Gateway error?

First, most causes sit in the upstream layer. The list below covers the reasons that official documentation mentions most often. The order is not a ranking, because it changes from site to site.

  • PHP-FPM, Node.js or the app service has crashed or never started.
  • The PHP-FPM worker pool is full, and new requests pile up.
  • Also, the reverse proxy may point to the wrong address or port.
  • Sometimes the application cuts the response short or sends an invalid header.
  • Memory ran out, and the operating system killed the application.
  • A firewall or wrong permissions block the link between proxy and upstream.
  • The CDN cannot connect to the origin server.

So there is no single magic fix. Following a diagnosis order gives you results much faster than guessing.

How do you check a 502 error as a visitor?

First, find out whether the problem is on your side or the site's side. Reload the page once, then open it in a private window. After that, try mobile data or another network. If the site fails on other networks too, then the server is the problem.

Here is a short checklist:

  1. Reload the page and wait a few minutes.
  2. Turn off tools such as a VPN, a proxy and an ad blocker.
  3. Try another device or network.
  4. Use our DNS lookup tool to check that the domain resolves to the right place.
  5. If the problem stays, tell the site owner or the host the time of the error.

Clearing the cache also helps sometimes. Since a 502 comes from the server, though, it rarely solves the problem.

What should a site owner try first?

If you own the site, the first question is this: when did it start, and what changed just before? For example, a plugin update, a theme change, a new cron job or a traffic spike often triggers the error.

Work through these steps in order:

  1. Open the hosting panel and look at resource use (CPU, RAM, process count).
  2. Disable the plugin or theme you updated last.
  3. Check maintenance mode and security plugin settings.
  4. If you use a CDN, pause it briefly and reach the origin server directly.
  5. Record the time, the address and a screenshot of the error.
  6. Open a support ticket with those details.

Also, if the error comes and goes, write that down. For example, an intermittent 502 often points to a resource limit or busy hours. A constant 502, however, usually points to a stopped service or a broken configuration. That distinction is the most valuable part of what you tell your host.

With a regular backup strategy, a way back is always at hand. A backup is also the fastest exit from plugin-related trouble.

Where does a server admin start the diagnosis?

If you run your own VPS, the order is simple. First, check that the services are alive. Then check whether the reverse proxy can reach the upstream. Finally, read the log. The commands below assume a common Debian or Ubuntu layout, so service names and log paths may vary by distribution.

sudo systemctl status nginx
sudo systemctl status php-fpm
sudo nginx -t
sudo tail -n 50 /var/log/nginx/error.log
ss -ltnp

On some distributions, the PHP-FPM service name carries a version number. To find the right name, first read the output of systemctl list-units --type=service. Likewise, the nginx log path can differ with the way you installed it.

Two kinds of log sentences help a lot:

  • Connection refused: Nothing listens at that upstream address.
  • Prematurely closed connection: The upstream closed the link before it finished the response.

The first usually suggests a stopped service. The second suggests a crash or a killed process.

What happens when PHP-FPM crashes or its pool fills up?

WordPress, Laravel and most PHP sites run behind nginx with PHP-FPM. If PHP-FPM is down, nginx cannot reach the upstream and returns a 502. The same happens, for example, when the socket PHP-FPM listens on differs from the one nginx tries to use.

A sneakier case, however, is a full pool. According to the PHP manual, pm.max_children sets the limit on simultaneous requests the pool can serve. When all workers are busy, new requests wait. As a result, if the wait grows long, you see timeouts and sometimes connection errors.

If the PHP-FPM log shows a warning like "server reached pm.max_children setting", the pool has hit its ceiling. However, that does not mean you should just raise the value. First, find out why a slow script or query keeps workers busy for so long.

Also, another common cause is a mismatch in the listen address. On the PHP-FPM side, the listen setting can be a Unix socket or an IP and port. The fastcgi_pass directive in nginx must point to the same address. So if you change one and forget the other, a 502 is unavoidable.

How do you calculate pm.max_children?

The PHP manual gives no fixed number for pm.max_children. Instead, the right value depends on your server memory and on how much memory each process uses. The logic is simple: divide the memory you can give to PHP by the average use of one process.

The numbers below are only an example calculation, not a measurement of your site:

  • Memory you can give to PHP on the server: 2 GB (example).
  • One PHP-FPM process uses about 50 MB on average (example).
  • Result: about 40 processes, so pm.max_children near 40.

First, measure the real average on live traffic. Use top or htop and look at the memory of one PHP-FPM child process. Then leave room for the operating system, the database and the cache. A value that is too high exhausts memory, and then the operating system kills processes. The result is a 502 again.

pm = dynamic
pm.max_children = 40
pm.max_requests = 500

The 500 here is an example too. The manual says pm.max_requests can respawn workers to work around memory leaks in third-party libraries.

How do nginx proxy timeouts affect 502 and 504 errors?

The nginx documentation says proxy_connect_timeout sets the time to establish a connection, and proxy_read_timeout sets the wait between two successive reads. Connect, read and send all default to 60 seconds. For FastCGI, the matching directives are fastcgi_connect_timeout and fastcgi_read_timeout.

Also, raising the numbers blindly is not a fix. Making a slow script wait 300 seconds keeps the visitor on a blank page longer. It also keeps PHP workers busy longer. Instead, find the source of the slowness first.

location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_connect_timeout 5s;
    proxy_read_timeout 60s;
}

The values in this snippet are examples. For jobs that really run long, such as reports, moving them to a background queue is a healthier approach.

Also note one more detail. The default of proxy_next_upstream is error timeout. So with several upstreams, nginx retries on those events. With a single upstream there is no backup, and the error goes straight to the visitor.

How does a reverse proxy 502 happen in Apache?

When Apache runs as a reverse proxy through mod_proxy, the same logic applies. If the upstream does not answer or sends an invalid header, Apache can return a 502. According to the official documentation, the default ProxyBadHeader value, IsError, returns a 502 on an invalid header.

The ProxyTimeout directive sets the network timeout for proxied requests. The documentation recommends it for a slow or buggy application server that hangs, so Apache can fail gracefully instead of waiting forever. Its default equals the Timeout value.

In panels such as cPanel, Apache and nginx can run together. As a result, the error can come from either layer. Therefore, without the logs, you cannot tell which one produced the 502. If you have no access to those logs on managed hosting, ask your provider for the relevant lines.

For a wider comparison, read our article on OpenLiteSpeed versus nginx.

Why do Node.js, PM2 and Next.js apps return a 502?

Node.js apps usually run on their own port behind nginx. If the app crashed, if the port differs, or if the process manager failed to restart it, nginx returns a 502. In practice, this is the most common 502 Bad Gateway cause in the Node world.

Check these points in order:

  1. Is the app process running? With PM2, pm2 status shows it.
  2. Does the app listen on the port that proxy_pass points to?
  3. Does the app listen only on IPv4 or only on IPv6? On some setups, the name localhost resolves to a different address, and the connection fails.
  4. Did the build finish successfully after the last deploy?
  5. Did the system kill the process because of low memory?

For setup details, read our guides on installing Node.js and deploying with nginx and systemd, managing apps with PM2 and deploying a Next.js app to a VPS. We do not repeat that material here, because those guides cover it in full.

How do you diagnose a 502 behind Cloudflare or a CDN?

According to Cloudflare's documentation, a 502 or 504 means Cloudflare cannot establish contact with your origin web server. You can see the error from two places, so the page style matters. An origin error appears on a Cloudflare-branded page. An error that Cloudflare itself produces appears as a blank page without branding.

That split tells you where to look:

  • Branded page: The problem sits at the origin. Work with your hosting provider.
  • Blank page without branding: The cause may be Cloudflare. One example in the documentation is an origin serving gzip content without updating the content-length header.

When you write to Cloudflare Support, they ask for the time and time zone, the affected URL and the output of your domain's /cdn-cgi/trace. Pausing the CDN briefly and going straight to the origin also shows which layer fails.

Do not share your origin server's real address on public pages. With a tool such as our IP lookup tool, verify only your own records.

How do Cloudflare 520 to 524 errors differ from a 502?

Besides 502 and 504, Cloudflare uses its own 52x codes. The official 5xx page defines each code in one line. For all of them, it advises contacting the hosting provider with the error code, the time and the affected URL.

CodeCloudflare's wordingWhat it means
520Web server returns an unknown errorThe origin gave an unreadable answer
521Web server is downThe origin refuses connections
522Connection timed outNo connection to the origin
523Origin is unreachablePossible routing or network issue
524A timeout occurredThe origin answered too slowly
525SSL handshake failedTLS with the origin failed
526Invalid SSL certificateThe origin certificate did not validate

In short, if you see a code between 520 and 526, you use Cloudflare, and the cause often sits at the origin. For 525 and 526, check your certificate with our SSL checker. We explain the basics in our article on SSL certificates.

How do you read the lines in an error log?

The log is the only source that names the real cause of a 502 Bad Gateway error. Typically, the nginx error log records an upstream problem in a sentence that contains the word "upstream". Then the last part of the sentence shows which stage failed.

  • "Connection refused" and "while connecting to upstream": The connection failed, because the service is down or the address is wrong.
  • "Upstream timed out" and "while reading response header": The upstream accepted the connection but sent no response header. A slow script or a stuck process is possible.
  • "Upstream prematurely closed connection": The upstream closed the link before the response ended. Think of a crash or low memory.
  • "Permission denied": The socket file is not accessible, so check the user and group settings.
  • "No such file or directory": The socket file is missing, because PHP-FPM is not running or the path differs.

The timestamp next to the line should match the time the visitor saw the error. Then you do not get lost in old, unrelated entries. Besides, if the log grows very fast, that is a warning in itself: a repeating error tires the server.

However, reading these records needs root access. On shared hosting, ask your provider for the lines in the relevant time window.

What should you check for a 502 on WordPress?

WordPress owners mostly see a 502 after a plugin or theme change. If you cannot reach the dashboard, you can rename the wp-content/plugins folder through a file manager or FTP. That disables every plugin, so you quickly see whether a plugin is the culprit.

Try this order:

  1. Find the plugin updated just before the error and disable it.
  2. If the problem stays, stop all plugins and turn them on one by one.
  3. Try switching to a default theme.
  4. Check the PHP version and the memory limit in the hosting panel.
  5. Review heavy cron jobs, backup plugins and import tasks.

A heavy plugin can hold many PHP workers for a long time. Then the pool fills up and a 502 follows. Therefore, keeping the plugin count reasonable is a good habit for both security and stability.

Otherwise, if the error continues and you have no server access, pass your findings to your provider. Do not make changes without a backup while you try to repair WordPress itself.

How does a 502 Bad Gateway error affect SEO and sales?

A short 502 Bad Gateway error does not hurt your rankings, but a long one does. Google Search Central says 5xx and 429 errors temporarily slow down crawling. In other words, the drop in crawl rate is proportional to the number of URLs that return a server error. You can read the details on Google's HTTP and network errors page.

On the same page, Google explains that indexed URLs are preserved at first. URLs that keep returning a server error eventually drop out of the index. Once the server returns a 2xx again, Google gradually raises the crawl rate.

However, the effect on e-commerce is more direct. For example, if the checkout returns a 502, shoppers abandon the cart. If you buy ad traffic, you still pay for every click that lands on the broken page. For that reason, think about page speed and availability in e-commerce together. For a wider picture, see our article on how site speed affects SEO.

During planned maintenance or a temporary closure, a 503 with a Retry-After header is more correct than a 502.

How do you prevent a 502 Bad Gateway error from coming back?

In short, a lasting fix means seeing the failure early and stopping one fault from taking down the whole site. Most of these jobs are things you do together with your provider.

  • Monitoring: Set up an uptime monitor that checks the home page and key pages from outside at regular intervals.
  • Automatic restart: Use systemd or PM2 so a crashed service comes back on its own.
  • Resource planning: Tune RAM and PHP worker count to real traffic.
  • Caching: Cache frequently requested pages to cut the load on the upstream. Our articles on OPcache and Redis versus Memcached cover this.
  • Safe deploys: Test changes in a staging environment before going live, and always take a backup.
  • Version fit: Check that plugin, theme and PHP versions work together before you update.

Also, do not forget attack traffic. For example, an abnormal number of requests can drain PHP workers. Layers such as Fail2ban and ModSecurity reduce that load.

When should you leave the work to your hosting provider?

Our honest answer: if server administration is not your job, do not tinker. A wrong configuration can turn one error into several, so be careful. In the situations below, go straight to your provider.

  • You use shared hosting or a managed VPS and have no root access.
  • The error spreads across the whole server, and several of your sites go down at once.
  • The logs show lines that point to disk, memory or network hardware.
  • You are about to edit a configuration file for the first time on a live store.
  • You risk making a wrong change without a backup.

Also, treat support quality as a criterion when you pick a host. We list these criteria in our guide on how to choose web hosting.

What should you include in a support ticket to your host?

Missing details slow support down, so be specific. Cloudflare says in its own documentation that it needs the error code, the time and the URL. The same approach works with every provider.

Add this information to your ticket:

  1. The time the error started and ended, with the time zone.
  2. The exact affected URL, and whether the error shows on all pages or only some.
  3. A screenshot of the error page.
  4. The change you made just before the error, such as a plugin, a theme or a deploy.
  5. If you use a CDN, the result when you reach the origin directly.
  6. A few relevant lines from the error log, if you have them.

Also, do not put passwords, keys or private data in the ticket. If you share log lines, remove any personal data first.

How do you read the quick diagnosis table?

The table below links each symptom to a likely cause and an owner. However, it is not a final verdict. Instead, treat it as a starting point for diagnosis.

SymptomLikely causeWho looks?
"Connection refused" in the logUpstream service stopped or wrong addressServer admin
"Prematurely closed connection" in the logThe app crashed or the process was killedAdmin and developer
pm.max_children warning in the PHP-FPM logThe worker pool is fullAdmin, sometimes the developer
Blank Cloudflare page without brandingProblem on the CDN sideSite owner, Cloudflare Support
Right after a plugin updateIncompatible plugin or themeSite owner
Only for you, not for othersLocal network, VPN, DNSVisitor

Use the table like a checklist. If the result is unclear, trust the sentence in the log.

How can our team help?

We are not a hosting company that offers server administration. Still, errors like a 502 touch the marketing side, because they directly affect your visibility and ad budget. Reading error windows together with search traffic and ad data, for example, helps you understand the loss.

If you plan a new site, see our web design service. For the technical visibility of your current site, we offer SEO consulting. For your online store, there is our e-commerce consulting. On infrastructure decisions, we work with your provider and help you define the right requirements.

For performance measurement, our article on testing site performance with Google Lighthouse is a good start. We also cover the server side of slowness in why your website is slow.

What should you remember about a 502 Bad Gateway error?

A 502 tells you something went wrong in the background, and the log tells you what. First rule out the visitor side. Then look at service status, reverse proxy settings and resource limits. If you use a CDN, the split between branded and unbranded error pages guides you.

Also, a lasting fix needs monitoring, automatic restarts and a realistic resource plan. Server administration takes expertise, so if you are unsure, going to your provider with the right details is the safest path.

Frequently Asked Questions

Whose fault is a 502 Bad Gateway error?
Most of the time it is a server-side problem, not the visitor's fault. MDN describes the error as something server owners and administrators should investigate. However, if you use a VPN or a custom network and the site opens for other people, you should also check your network, DNS and proxy settings.
Does a 502 Bad Gateway error fix itself?
Sometimes it does. If the upstream service was briefly too busy to answer, or restarted itself, the error may clear within minutes. If it continues, a service may have crashed, a worker pool may be full or a configuration may be broken. In that case, check the logs or contact your host with the exact time.
What is the difference between a 502 and a 504 error?
A 502 shows that the gateway received an invalid response from the upstream. A 504 shows that the gateway did not get a timely response. So a 502 usually relates to a broken or refused connection, while a 504 relates to slowness or a timeout. Some stacks apply the split differently, so read the log sentence.
Does a 502 error hurt SEO?
A short error usually does not hurt rankings. According to Google Search Central, 5xx errors temporarily slow crawling, and URLs that keep returning a server error eventually drop out of the index. So you should fix a long 502 quickly. For planned maintenance, a 503 with a Retry-After header is the better choice.
What should I do about a 502 on my WordPress site?
First note when the error started and which plugin or theme you updated just before. Then roll back the latest change, check resource use and, if you use a CDN, try to reach the origin directly. If the problem stays, open a support ticket with those details, and do not tinker with server settings yourself.
Does raising pm.max_children fix a 502?
Not always. If the pool is full, a higher value can help. If the server lacks memory, though, the system kills processes and the 502 returns. First measure the average memory of one PHP process, then calculate the value from your memory. If a slow script or query exists, fixing it is the real solution.
  • 502 bad gateway
  • http error codes
  • php-fpm
  • nginx
  • cloudflare
  • server error
  • reverse proxy
Share:
Talha Aslan

Google Partner digital marketing expert. Hands-on with SEO, Google Ads, web design and e-commerce projects since 2012; every post here comes from that experience.

Next project

Let's talk about your project.

Your brief goes straight to Talha Aslan and team: strategy led by Talha, delivery by an experienced team. The first consultation is free; we listen and come back with a clear roadmap.