使用PHP set_time_limit()防止nginx 504网关超时

问题描述 投票:101回答:10

当我的PHP脚本运行时间超过平常时,我从nginx收到504超时消息。 set_time_limit(0)似乎没有阻止这一点!在nginx上运行php5-fpm时它不起作用吗?如果是这样,那么设定时限的正确方法是什么?

错误:

504 Gateway Time-out
nginx/1.2.7
php nginx fastcgi
10个回答
178
投票

有几种方法可以设置php-fpm的超时。在/etc/php5/fpm/pool.d/www.conf我添加了这一行:

request_terminate_timeout = 180

此外,在/etc/nginx/sites-available/default中,我将以下行添加到相关服务器的位置块:

fastcgi_read_timeout 180;

整个位置块看起来像这样:

location ~ \.php$ {
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_read_timeout 180;
    include fastcgi_params;
} 

现在只需重新启动php-fpm和nginx,对于少于180秒的请求,不应再有超时。


-7
投票

我用config APACHE解决了这个问题!所有方法(在本主题中)对我来说都不正确...然后我尝试使用chanche apache config:

Timeout 3600

然后我的脚本工作了!


45
投票

试试这个link,它有一个更好的解决方案,如何解决这个问题。所以步骤是:

  1. 打开位于nginx.conf目录中的/etc/nginx文件。
  2. http {部分下面添加以下代码: client_header_timeout 3000; client_body_timeout 3000; fastcgi_read_timeout 3000; client_max_body_size 32m; fastcgi_buffers 8 128k; fastcgi_buffer_size 128k; 注意:如果已存在,请更改值。
  3. 重新加载Nginx和php5-fpm。 $ service nginx reload $ service php5-fpm reload 如果错误仍然存​​在,请考虑增加值。

9
投票

您不能使用PHP来防止nginx发出的超时。

要配置nginx以允许更多时间,请参阅proxy_read_timeout directive


8
投票

正确答案是在Nginx配置中增加fastcgi_read_timeout。 就那么简单!


5
投票
 sudo nano /etc/nginx/nginx.conf

将这些变量添加到nginx.conf文件中:

http {  
  # .....
  proxy_connect_timeout       600;
  proxy_send_timeout          600;
  proxy_read_timeout          600;
  send_timeout                600;
}

然后重启:

service nginx reload

1
投票

你需要在ngx_http_proxy_module中添加额外的nginx指令(对于nginx.conf),例如:

proxy_read_timeout 300;

基本上,nginx proxy_read_timeout指令更改了代理超时,FcgidIOTimeout用于安静太长的脚本,而FcgidBusyTimeout用于执行时间太长的脚本。

此外,如果您使用的是FastCGI应用程序,请同时增加以下选项:

FcgidBusyTimeout 300
FcgidIOTimeout 250

然后重新加载nginx和PHP5-FPM。

Plesk

在Plesk中,您可以在附加nginx指令下的Web服务器设置中添加它。

对于FastCGI,请检查HTTP附加指令下的Web服务器设置。

见:How to fix FastCGI timeout issues in Plesk?


1
投票

在这种情况下可以发生三种超时。可以看出,每个答案仅关注这些可能性的一个方面。因此,我想把它写下来,以便将来访问这里的人不需要随机检查每个答案并获得成功而不知道哪个有效。

  1. 超时请求者的请求 - 需要设置超时标头(请参阅请求库中的标头配置)
  2. 在发出请求时从nginx超时(在转发到代理服务器之前)例如:正在上传大量文件
  3. 转发到代理服务器后超时,服务器不及时回复nginx。例如:在服务器上运行的耗时的脚本

因此,每个问题的修复如下。

  1. 设置超时标头例如:在ajax中

$.ajax({
    url: "test.html",
    error: function(){
        // will fire when timeout is reached
    },
    success: function(){
        //do something
    },
    timeout: 3000 // sets timeout to 3 seconds
});
  1. nginx客户端超时 http{ #in seconds fastcgi_read_timeout 600; client_header_timeout 600; client_body_timeout 600; }
  2. nginx代理服务器超时 http{ #Time to wait for the replying server proxy_read_timeout 600s; }

所以使用你需要的那个。也许在某些情况下,您需要所有这些配置。我需要。


0
投票

由于您使用的是php-fpm,因此您应该利用fastcgi_finish_request()来处理您知道可能需要更长时间的请求。


0
投票

使用php-fpm或类似的进程管理器时,使用set_time_limit(0)是没用的。

使用set_time_limit时底线不是使用php-fpm,增加执行超时,检查这个tutorial

© www.soinside.com 2019 - 2024. All rights reserved.