How To Fix 502 Bad Gateway Error on Nginx

Fix 502 Bad Gateway Error on Nginx

In this tutorial, we will show you how to fix 502 bad gateway errors on the Nginx web server. If you run an Nginx web server you may have already encountered the annoying 502 bad gateway errors. This is a pretty common error, is generated most probably by the PHP or  FastCGI buffer and timeouts settings. This tutorial shows you how to fix Nginx 502 bad gateway on the Nginx webserver. This post shows how to fix this problem, and the configuration option to prevent it from occurring again on reboot.

This article assumes you have at least basic knowledge of Linux, know how to use the shell, and most importantly, you host your site on your own VPS. The installation is quite simple and assumes you are running in the root account, if not you may need to add ‘sudo‘ to the commands to get root privileges. I will show you through the step by step solve 502 bad gateway error on the Nginx web server.

Fix 502 Bad Gateway Error on Nginx

Step 1. First, check the data log Nginx webserver.

You can see in greater detail what the error specifically entails by going to your web server’s error log file. All error and diagnostic information are stored in this file making it a valuable resource to check when you need more details about a particular error. You can locate this file in Nginx by going to /var/log/nginx/error.log.

Step 2. Solve 502 Bad Gateway Issues.

  • Method 1. Changes in Nginx Config.

Run the following command to edit Nginx conf:

sudo nano /etc/nginx/nginx.conf
http {
    fastcgi_buffers 8 16k;
    fastcgi_buffer_size 32k;

Once done, restart Nginx service to take effect:

sudo nginx -t
sudo systemctl restart nginx
  • Method 2. Change PHP-FPM to listen on a Unix socket or TCP socket.
nano /etc/php-fpm.d/www.conf
listen = /var/run/php5-fpm.sock


listen =

After that, restart PHP-FPM to change the effect:

sudo systemctl restart php-fpm

If you are configuring php-fpm to listen on a Unix socket, you should also check that the socket file has the correct owner and permissions.

chmod 0660 /var/run/php5-fpm.sock
chown www-data:www-data /var/run/php5-fpm.sock
  • Method 3. Disable APC.

APC caching can cause 502 Bad Gateway issues under particular environments causing segmentation faults. I highly suggest using Memcache(d), but XCache is also a good alternative.

Congratulations! You have successfully solved 502 bad gateway issues. Thanks for using this tutorial to fix 502 bad gateway issues on the Linux system. For additional help or useful information, we recommend you to check the official Nginx website.

Nginx Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “Nginx Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!