Nginx

是否可以基於每個位置在 nginx 中延長 504 超時

  • March 23, 2020

是否可以在位置塊中設置超時指令以防止 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 秒後發生超時。PHP 配置為允許腳本執行直到完成(set_time_limit(0))

如果我fastcgi_read_timeout在主~ /.php {}塊中設置,這可以解決問題。

我不想為所有腳本設置全域超時。

**首先,看一下嵌套位置。**不考慮您的第二個位置塊的原因是,當 nginx 匹配一個位置時,它會停止。所以,http://ubuntu-vm.test-api/someurlpath如果相應文件夾中有 index.php,則只匹配location ~ \.php$!

我偶然發現了這篇有趣的部落格文章

總結一下,你需要:

  1. 增加max_execution_timephp.ini 中的配置變數。
  2. 增加request_terminate_timeoutphp-fpm的配置變數。
  3. 在 nginx 配置文件中設置fastcgi_read_timeout你想要的位置。

問題是你不能告訴 php-fpm 只為那個位置使用不同的配置文件。

但是,您可以在 nginx 配置中設置 php.ini 配置變數,如下所示:

fastcgi_param PHP_VALUE "max_execution_time=1000";

引用自:https://serverfault.com/questions/604665