skip to content
Skesov.com

Configuring Timeouts in Nginx and PHP: Fixing 504 Gateway Time-out

/ 2 min read

Table of Contents

The 504 Gateway Time-out error means that Nginx did not receive a response from the backend (such as PHP-FPM or another proxied server) within the allocated time. This frequently occurs when importing large databases, generating heavy reports, or processing file uploads.

To allow scripts to finish execution, you must synchronize timeouts across all components in the request chain.

1. Nginx Timeout Settings

Nginx has several parameters to control wait times. Add them to your server or location block (e.g., /etc/nginx/sites-available/default):

server {
# Time during which a keep-alive client connection will stay open
keepalive_timeout 65;
location ~ \.php$ {
# ... standard fastcgi settings ...
# Maximum time to wait for a response from PHP-FPM
fastcgi_read_timeout 300s;
}
# If you are proxying requests to another service (e.g., Node.js or Python)
location /api/ {
proxy_read_timeout 300s;
proxy_connect_timeout 75s;
}
}

2. PHP Timeout Settings

Even if Nginx is configured to wait for 5 minutes (300 seconds), PHP might forcefully terminate the script early due to its own internal limits.

Changes in php.ini

Edit your php.ini (e.g., /etc/php/8.3/fpm/php.ini):

; Maximum execution time of a script in seconds
max_execution_time = 300
; Maximum time allowed to parse request data (POST/GET)
max_input_time = 300

Changes in PHP-FPM Pool

If you use PHP-FPM, open your pool configuration (/etc/php/8.3/fpm/pool.d/www.conf) and uncomment the safety termination parameter:

; Forcefully terminate a worker process if it hangs longer than this time.
; Prevents stuck scripts that ignore max_execution_time.
request_terminate_timeout = 300s

The Ideal Timeout Rule

Ensure your limits form a logical chain. Nginx should wait slightly longer than PHP-FPM executes so that it can receive a proper response (or a handled error) from the backend, rather than blindly dropping the connection.

Rule of thumb: request_terminate_timeout (PHP) ≤ fastcgi_read_timeout (Nginx)

Applying Changes

Test and restart your services:

Terminal window
sudo nginx -t
sudo systemctl restart nginx
sudo systemctl restart php8.3-fpm