是否有可能在每个位置的基础上延长Nginx的504超时

是否可以在一个位置块中设置超时指令,以防止nginx从长时间运行的PHP脚本(PHP-FPM)返回504?

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; } 

在向example.com/someurlpath发出请求时,这不起作用。 大约60秒后发生超时。 PHPconfiguration为允许脚本运行直到完成(set_time_limit(0))

如果我在~ /.php {}块中设置了fastcgi_read_timeout ,就可以解决这个问题。

我不想为所有脚本设置全局超时。

首先,看看嵌套的位置。 不考虑你的第二个位置块的原因是因为当nginx匹配一个位置时,它停止。 所以, http://ubuntu-vm.test-api/someurlpath ,如果在相应的文件夹里有一个index.php,只匹配location ~ \.php$

我偶然发现了这个有趣的博客文章

总结这一点,你需要:

  1. 增加php.ini中的max_execution_timeconfigurationvariables。
  2. 增加php-fpm的request_terminate_timeoutconfigurationvariables。
  3. fastcgi_read_timeout设置在你想要的位置,在nginxconfiguration文件中。

麻烦的是你不能告诉php-fpm只使用一个不同的configuration文件。

但是,您可以在nginxconfiguration中设置一个php.iniconfigurationvariables,如下所示:

 fastcgi_param PHP_VALUE "max_execution_time=1000"; 

我遇到了同样的问题,虽然我认为你可以使用Nginxconfiguration来设置每个位置的fastcgi_read_timeout,但是最终以这种方式正确configuration位置会变得很复杂。 然后,如果你不设置PHP的max_execution_time,它可能仍然超时。

我发现一个更好的解决scheme是设置它,以便Nginx的超时不被真正使用,并让PHP处理超时而不是(像其他服务器,如mod-Apache和命令行一样)。

因此,在你的Nginxconfiguration的“location〜.php $”部分,将request_terminate_timeout设置为一个非常高的值(或者更好,将其设置为0来禁止超时)。 还可以将fastcgi_read_timeout设置为您可能希望运行任何脚本的最高秒数。

然后通过在php.ini中设置max_execution_time来设置一个默认值来对其进行微调。 现在,当您想要允许运行很长时间的脚本时,请在这些脚本中使用set_time_limit()PHP命令。

您可以在任何locationserverhttp块中设置超时,如nginx文档中所示。 他们将从包含块inheritance,这就是为什么你张贴的片段不起作用。

你有没有尝试在该位置设置fastcgi_pass

 location { fastcgi_pass 127.0.0.1:9000; fastcgi_read_timeout 100000s; }