如何使用 nginx 和 php 后端修复重定向到尾部斜线

How to fix redirect to trailing slash with nginx and php backend

就像这个 thread 我 运行 遇到尾部斜杠的相同问题。

目录/var/www/services 包含多个后端服务。 例如,我请求 GET /customer?arg1=1&arg2=2 nginx 将始终将我重定向到 /customer/?arg1=1&arg2=2.

Nginx 日志输出:

172.18.0.6 - - [29/May/2019:14:47:32 +0000] "GET /customer?limit=1&filter%5Bemail%5D=somemail%40gmail.com&filter%5BwebsiteId%5D=1 HTTP/1.1" 301 170 "-" "GuzzleHttp/6.3.3 curl/7.29.0 PHP/7.0.33"
172.18.0.6 - - [29/May/2019:14:47:32 +0000] "GET /customer/?limit=1&filter%5Bemail%5D=somemail%40gmail.com&filter%5BwebsiteId%5D=1 HTTP/1.1" 200 12 "-" "GuzzleHttp/6.3.3 curl/7.29.0 PHP/7.0.33"

所有其他请求,如 customer/count 按预期工作。

我怎样才能避免这种不良行为?

配置如下:

server {
        listen 80;
        listen 443 ssl;
        server_name api.local;
        root /var/www/services;

        ssl_certificate  /etc/ssl/certs/optimax.crt;
        ssl_certificate_key /etc/ssl/certs/optimax.key;
        ssl_dhparam /etc/ssl/certs/optimax.pem;

        location ~ ^/(?<ms_dir>[^/]+)/(.*)$ {
                root /var/www/services/$ms_dir/public;
                set $ms_request ;
                try_files $uri /index.php$is_args$args;
        }

        location ~ /index\.php(/|$) {
                fastcgi_pass php72:9001;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                include fastcgi_params;
                fastcgi_param REQUEST_URI $ms_request;
                fastcgi_param SCRIPT_FILENAME $realpath_root/$ms_dir/public$fastcgi_script_name;
                fastcgi_param DOCUMENT_ROOT $realpath_root/$ms_dir/public;
        }

        access_log /dev/stdout;
        error_log /dev/stderr;
        rewrite_log on;
}

Richard Smith's 建议非常有效。

更新配置如下:

server {
        listen 80;
        listen 443 ssl;
        server_name api.local;
        root /var/www/services;

        ssl_certificate  /etc/ssl/certs/optimax.crt;
        ssl_certificate_key /etc/ssl/certs/optimax.key;
        ssl_dhparam /etc/ssl/certs/optimax.pem;

        location ~ /index\.php(/|$) {
                fastcgi_pass php72:9001;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                include fastcgi_params;
                fastcgi_param REQUEST_URI $ms_request;
                fastcgi_param SCRIPT_FILENAME $realpath_root/$ms_dir/public$fastcgi_script_name;
                fastcgi_param DOCUMENT_ROOT $realpath_root/$ms_dir/public;
        }

        location ~ ^/(?<ms_dir>[^/]+)(?:/(.*))$ {
                root /var/www/services/$ms_dir/public;
                set $ms_request ;
                try_files $uri /index.php$is_args$args;
        }

        access_log /dev/stdout;
        error_log /dev/stderr;
        rewrite_log on;
}