我目前有以下 NGINX 配置:
server {
[...]
location / {
try_files $uri $uri/ =404;
}
location /app1 {
index index.php;
try_files $uri $uri/ @app1;
}
location @app1 {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root/app1/index.php;
fastcgi_split_path_info ^(.app1)(.*)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_pass unix:/run/php/php7.3.sock;
}
location /app2 {
index index.php;
try_files $uri $uri/ @app2;
}
location @app2 {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root/app2/index.php;
fastcgi_split_path_info ^(.app2)(.*)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_pass unix:/run/php/php7.3.sock;
location ~* \.php$ {
fastcgi_pass unix:/run/php/php7.3.sock;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
}
location ~ /\.ht {
deny all;
}
}
正如您所看到的,我目前为子目录启用了 PHP-Routing 手册/应用程序1和/app2但我的目标是为每个第一级子目录动态启用 PHP-Routing,例如
/foo/bar/baz应路由至/foo/index.php?/bar/baz
无需在 NGINX 配置中手动配置 /foo 位置。
有人能帮我解决这个问题吗?
答案1
你可以使用这样的方法:
location / {
try_files $uri $uri/ @php;
}
location @php {
rewrite ^(/[^/]+)(/.+)$ $1/index.php?$2? last;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass unix:/run/php/php7.3.sock;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $request_filename;
}
命名位置将重写/foo/bar/baz
为/foo/index.php?/bar/baz
。请注意,默认情况下,参数/bar/baz
将出现在 中,$_SERVER['QUERY_STRING']
而不是$_SERVER['PATH_INFO']
像以前那样。