如何为 Laravel 项目中的某些路由设置超时?

Jub*_*bin 1 configuration timeout nginx laravel

我有一个关于 Laravel 的项目。我有网页路由和api路由。我的问题是:如何为这两组设置不同的超时时间?

我尝试使用中间件,只是玩玩set_time_limit,但没有用。

所以我想我可以通过我的 Nginx vhost 文件来做到这一点,我有点坚持这一点。到目前为止,我是如何结束的:

server {
    listen 80;
    listen 443 ssl http2;
    server_name mysiste;
    root "/home/vagrant/www/mysite/public";

    index index.html index.htm index.php;

    charset utf-8;

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


    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;
    error_log  /var/log/nginx/mysite-error.log error;

    sendfile off;

    client_max_body_size 100m;

    location ~ \.php$ {
         fastcgi_split_path_info ^(.+\.php)(/.+)$;
         fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
         fastcgi_index index.php;
         include fastcgi_params;
         fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

         fastcgi_intercept_errors off;
         fastcgi_buffer_size 16k;
         fastcgi_buffers 4 16k;

         fastcgi_connect_timeout 300;
         fastcgi_send_timeout 300;
         fastcgi_read_timeout 300;
     }

     location ~ ^/api/v1 {
         try_files $uri $uri/ /index.php?$query_string;
         client_body_timeout 1;
         send_timeout 1;
         fastcgi_connect_timeout 300;
         fastcgi_send_timeout 300;
         fastcgi_read_timeout 300;
     }

     location ~ /\.ht {
         deny all;
     }
}
Run Code Online (Sandbox Code Playgroud)

(当然,我将超时设置为1只是为了做我的研究)。

有没有人知道如何解决这个问题?

谢谢 !

mew*_*ewm 6

您的配置不起作用的原因是因为try_files指令重定向到您的location ~ \.php$. 为避免这种情况,您必须try_files在特定路线中删除并硬编码您的fastcgi_param SCRIPT_FILENAME.

这就是我解决这个问题的方法,我不得不为用于视频上传的路由设置更长的超时时间:

  • php.ini max_execution_time 到 30s
  • php-fpm 的默认 request_terminate_timeout(为 0)
  • set_time_limit(1800);在我的 Laravel 控制器的顶部(从 解析/api/posts

然后像这样使用 nginx 位置:

location ~ ^/api/posts {
    include fastcgi_params;
    fastcgi_connect_timeout 30s;
    fastcgi_read_timeout 1800s;
    fastcgi_send_timeout 1800s;
    fastcgi_buffers 256 4k;
    fastcgi_param SCRIPT_FILENAME '${document_root}/index.php';
    fastcgi_pass php:9000;
}

location ~ \.php$ {
    try_files $uri /index.php?$query_string;
    include fastcgi_params;
    fastcgi_connect_timeout 30s;
    fastcgi_read_timeout 30s;
    fastcgi_send_timeout 30s;
    fastcgi_buffers 256 4k;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass php:9000;
}
Run Code Online (Sandbox Code Playgroud)

您可能需要为您的用例调整参数。

作为记录,我使用 PHP 7.3 和 nginx 1.12.2