How to Fix Nginx 502 Bad Gateway on Debian 11
The Root Cause
On Debian 11, the “502 Bad Gateway” error often signifies that Nginx, acting as a reverse proxy, cannot connect to the upstream application server, typically PHP-FPM. This frequently stems from a mismatch in the PHP-FPM socket path specified in Nginx versus the actual PHP-FPM listening configuration, or incorrect file permissions preventing Nginx (running as www-data) from accessing the PHP-FPM socket.
Quick Fix (CLI)
# 1. Check the status of PHP-FPM (replace '8.1' with your installed PHP version, e.g., '7.4')
sudo systemctl status php8.1-fpm
# If PHP-FPM is not running or shows errors, restart it
sudo systemctl restart php8.1-fpm
# 2. Check the status of Nginx
sudo systemctl status nginx
# Restart Nginx to ensure it picks up any potential changes or clears transient issues
sudo systemctl restart nginx
# 3. Check Nginx error logs for more specific clues (tail the file to see real-time errors)
sudo tail -f /var/log/nginx/error.log
Configuration Check
The most common cause is a mismatch in the PHP-FPM socket path between Nginx and PHP-FPM’s configuration.
-
Nginx Site Configuration: Edit your Nginx site configuration file. This is typically located in
/etc/nginx/sites-available/and symlinked to/etc/nginx/sites-enabled/. Replaceyour_site.confwith your actual configuration file name.sudo nano /etc/nginx/sites-available/your_site.confInside the
location ~ \.php$block, look for thefastcgi_passdirective. Ensure it points to the correct PHP-FPM Unix socket path.Example Nginx line to check/change:
# old or incorrect # fastcgi_pass 127.0.0.1:9000; # fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # Correct for typical Debian 11 PHP 8.1 setup fastcgi_pass unix:/run/php/php8.1-fpm.sock; -
PHP-FPM Pool Configuration: Edit the PHP-FPM pool configuration file. Replace
8.1with your PHP version. The default pool is usuallywww.conf.sudo nano /etc/php/8.1/fpm/pool.d/www.confLook for the
listendirective. This must match thefastcgi_passpath in your Nginx configuration. Also, ensurelisten.ownerandlisten.groupallow Nginx to access the socket. Nginx typically runs aswww-data.Example PHP-FPM lines to check/change:
; old or incorrect ; listen = 127.0.0.1:9000 ; listen = /var/run/php/php7.4-fpm.sock ; Correct for typical Debian 11 PHP 8.1 setup listen = /run/php/php8.1-fpm.sock listen.owner = www-data listen.group = www-data
After making any changes, save the files and then check Nginx configuration syntax and restart both services:
sudo nginx -t
sudo systemctl restart php8.1-fpm
sudo systemctl restart nginx
Verification
# 1. Check the status of both services again
sudo systemctl status php8.1-fpm
sudo systemctl status nginx
# 2. Use curl to make a request to your web server (replace 'localhost' with your domain if accessing externally)
curl -I http://localhost
# You should see an HTTP 200 OK status code. If you still see a 502, re-examine the Nginx error logs.