我正在开发一个通过 Nginx 托管的 Laravel 应用程序,该应用程序正在替换在 Apache 2.2 上运行的旧系统。
新系统必须支持旧系统当前支持的所有url。
大多数网址都是这样的,并且工作正常:
https://somesite.com/some/path?someProp=1
但是,某些 url 有一个尾随反斜杠和一个查询字符串,如下所示:
https://somesite.com/some/path/?someProp=1
(虽然这样的链接肯定是不好的做法,但应用程序必须支持它们才能与其他相关系统向后兼容)。
在我的应用程序中,我发现当 url 有一个尾随反斜杠和一个查询字符串时,查询字符串和路径会在某处被破坏,例如,给定以下代码:
public function boot(): void
{
$uri = $_SERVER['REQUEST_URI'];
$query = $_SERVER['QUERY_STRING'];
}
对于没有斜杠的网址,我得到:
$uri === https://somesite.com/some/path?someProp=1
$query === someProp=1
但是对于带有斜杠的网址,我得到:
$uri === https://somesite.com/some/path//1
$query === ''
当 url 可能包含尾部反斜杠和查询字符串时,如何配置 Nginx 以正确设置 $request_uri 和 $query_string 值?
Nginx 服务器配置:
server {
listen 80;
listen 443 ssl;
server_name somesite.com;
ssl_certificate /etc/ssl/wildcard/tls.crt;
ssl_certificate_key /etc/ssl/wildcard/tls.key;
root /home/httpd/htdocs/public;
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php$ {
include includes/php-fpm.conf;
fastcgi_pass unix:/socket/monolith.php-fpm.sock;
fastcgi_param PHP_VALUE "auto_prepend_file=None
auto_append_file=None";
}
}
php-fpm.conf
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_param HTTP_PROXY "";
fastcgi_index index.php;
include fastcgi_params;
fastcgi_buffer_size 128k;
fastcgi_buffers 4 256k;
fastcgi_busy_buffers_size 256k;
#fixes timeouts
fastcgi_read_timeout 600;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
#astcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param SCRIPT_URL $uri;
fastcgi_param SCRIPT_URI $scheme://$http_host$uri;
fastcgi_params:
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;
fastcgi_param REQUEST_SCHEME $scheme;
fastcgi_param HTTPS $https if_not_empty;
fastcgi_param GATEWAY_INTERFACE CGI/1.1;
fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;
fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;
# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param REDIRECT_STATUS 200;