Solving the errror “504 Gateway Timeout” with NGINX and PHP

445 0

This post is also available in: Português

One of the most common errors for those who use Nginx as a webserver is the “504 Gateway Timeout” error. This error is usually generated when the response time of the server responsible for processing the request behind Nginx, in this case PHP, takes too long to send such a response. To fix this error, changes need to be made in both Nginx and PHP-FPM.

The way the “504 Gateway Timeout” error appears in the browser varies depending on the version of Nginx and the site configurations. The most common ones are:

  • “504 Gateway Timeout”
  • “504 Gateway Time-Out”
  • “504 Gateway Timeout NGINX”
  • “Nginx 504 Gateway Timeout”
  • “HTTP 504 Gateway Timeout”
  • “HTTP 504 Error”
  • “HTTP 504”
  • “Gateway Timeout (504)”

Changes in PHP

For those using php-fpm as a backend for Nginx, the following changes need to be made:

Change the max_execution_time in php.ini (In Ubuntu the php.ini is located in /etc/php/8.1/fpm/php.ini) to:

max_execution_time = 300

It is also necessary to change the request_terminate_timeout parameter in /etc/php/8.1/fpm/pool.d/www.conf to:

request_terminate_timeout = 300

Changes in Nginx

In the configuration of your virtual host in Nginx, add the fastcgi_read_timeout variable as indicated below:

location ~ .php$ {
    root /var/www/sites/nginxtips.com;
    try_files $uri =404;
    fastcgi_pass unix:/tmp/php5-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
    fastcgi_read_timeout 300;
}

Next, simply restart both php-fpm and Nginx, so that the request execution time limit is set to 5 minutes (300 seconds). If the error persists, it is just a matter of adjusting the values:

sudo service nginx restart
sudo service php8.1-fpm restart
(Visited 68 times, 1 visits today)

Elisio Leonardo

Elisio Leonardo is an experienced Web Developer, Solutions Architect, Digital Marketing Expert, and content producer with a passion for technology, artificial intelligence, web development, and entertainment. With nearly 15 years of writing engaging content on technology and entertainment, particularly Comic Book Movies, Elisio has become a trusted source of information in the digital landscape.