Is it possible to extend a 504 timeout in nginx on a per location basis

codecowboy asked:

Is it possible to set timeout directives within a location block to prevent nginx returning a 504 from a long running PHP script (PHP-FPM)?

server
{
  listen 80;
  server_name ubuntu-vm.test-api;
  root /home/me/Sites/path/to/site/; 
  index index.php;

  location / {
    try_files $uri $uri/ /index.php?$query_string;
  }

  location ~ .php$ {


    try_files $uri =404;

    # Fix for server variables that behave differently under nginx/php-fpm than typically expected
    fastcgi_split_path_info ^(.+.php)(/.+)$;

    # Include the standard fastcgi_params file included with nginx
    include fastcgi_params;
    fastcgi_param  PATH_INFO        $fastcgi_path_info;
    fastcgi_index index.php;

    # Override the SCRIPT_FILENAME variable set by fastcgi_params
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;

    # Pass to upstream PHP-FPM; This must match whatever you name your upstream connection
    fastcgi_pass unix:/var/run/php5-fpm.sock;

    }

    location /someurlpath {

    try_files $uri $uri/ /index.php?$query_string;

    # Fix for server variables that behave differently under nginx/php-fpm than typically expected
    fastcgi_split_path_info ^(.+.php)(/.+)$;

    # Include the standard fastcgi_params file included with nginx
    include fastcgi_params;
    fastcgi_param  PATH_INFO        $fastcgi_path_info;
    fastcgi_index index.php;

    # Override the SCRIPT_FILENAME variable set by fastcgi_params
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;

    # Pass to upstream PHP-FPM; This must match whatever you name your upstream connection
    fastcgi_pass unix:/var/run/php5-fpm.sock;

    fastcgi_read_timeout 100000s;
    }

    error_log /var/log/nginx/my_api_error.log;
    access_log /var/log/nginx/my_api_access.log;
}

This has no effect when making a request to example.com/someurlpath. The timeout occurs after approximately 60 seconds. PHP is configured to allow the script to run until completion (set_time_limit(0))

If I set the fastcgi_read_timeout in the main ~ /.php {} block this resolves the issue.

I don’t want to set a global timeout for all scripts.

My answer:


You can set the timeouts in any location, server or http block, as shown in the nginx documentation. They will be inherited from the containing block, which is why the snippet you posted did not work.


View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.