Fix "502 Bad Gateway" on Your Website
502 Bad Gatewaynginxupstream prematurely closedA 502 means your web server (nginx) reached the backend (PHP-FPM, an app server) but got an invalid or no response. The web server is fine — the thing behind it failed. Here's how to fix it.
Cause 1: PHP-FPM is down
The most common cause. If the PHP-FPM service crashed or isn't running, nginx has nothing to talk to. Restart it and check the logs:
systemctl status php-fpm # or php8.x-fpm
systemctl restart php-fpm
tail -50 /var/log/nginx/error.log
Cause 2: the backend timed out
A slow script (or a long DB query) that exceeds the proxy timeout returns a 502. The nginx error log shows "upstream timed out" or "prematurely closed". Fix the slow request, or raise the timeout if the work is legitimately long.
Cause 3: wrong socket / port
If nginx points to a PHP-FPM socket or port that doesn't match FPM's config, every request 502s. Make sure fastcgi_pass matches FPM's listen directive.
502 = the backend gave a bad/no response (often crashed). 504 = the backend took too long (a timeout). They point at different fixes — see our 504 guide.
The clean checklist
- Check the nginx error log — it names the real cause.
- Restart PHP-FPM (or your app backend) and confirm it's running.
- Look for a crashed backend (out of memory? see the OOM killer).
- Verify
fastcgi_passmatches FPM's listen socket/port.
502 = the backend failed. Restart PHP-FPM, read the nginx error log, and fix the crashed or mismatched backend.
Web hosting that stays up
Our managed web hosting runs and monitors PHP-FPM for you on NVMe, with DDoS protection included.
Frequently asked questions
What does 502 Bad Gateway mean?
Nginx reached the backend (PHP-FPM or an app server) but got an invalid or empty response — usually because the backend crashed, timed out, or is misconfigured. The web server itself is fine.
How do I fix a 502 error?
Check and restart PHP-FPM (or your app backend), read the nginx error log for the real reason, make sure the backend isn't out of memory, and confirm nginx's fastcgi_pass matches FPM's listen socket.
What's the difference between 502 and 504?
502 means the backend returned a bad or no response (often crashed); 504 means it took too long and timed out. They have different fixes — a crash vs a slow request.
Related articles
Fix "500 Internal Server Error" on Your Website
A 500 error on your site? The usual causes — .htaccess, file permissions, PHP — and how to fix them.
Read fix Web HostingHow to Point a Domain to Your Server (DNS A Record)
How to point a domain at your server with an A record — and why it doesn't work instantly.
Read fix Web HostingFix Email Going to Spam (SPF, DKIM & DMARC Explained)
Mail landing in spam? Set SPF, DKIM and DMARC correctly so your email reaches the inbox.
Read fix