【发布时间】:2022-01-14 03:56:56
【问题描述】:
我有一个 Web 服务器,它有两个 PHP 文件,index.php 和 controller.php,后者使用 p(用于页面)参数处理所有非 / 请求,例如
/controller.php?p=some_page
以下 nginx 配置运行良好:
server {
listen 80;
index index.php index.html;
server_name localhost;
error_log /var/log/nginx/error.log;
access_log /var/log/nginx/access.log;
root /code;
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass php:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
}
但是,我现在想清理 URL,并希望 / 转到 index.php 和 /some_page 转到 /controller.php?p=some_page。
这是我正在尝试的新配置:
server {
listen 80;
index index.php index.html;
server_name localhost;
error_log /var/log/nginx/error.log;
access_log /var/log/nginx/access.log;
root /code;
# this is new, and makes index.php handle /
location / {
index index.php;
try_files $uri $uri/ =404;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass php:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
# this is new, but doesn't work.
location @rewrites {
if ($uri ~* ^/([0-9a-z_]+)$) {
set $page_to_view "/controller.php?p=$1";
rewrite ^/([0-9a-z_]+)$ $scheme://$http_host/controller.php?p=$1 last;
}
}
}
浏览器地址栏显示如下:
- http://localhost:8080/some_page (initial request)
- http://localhost:8080/controller.php?p=some_page (first redirect one second later)
- https://localhost/some_page/ (final redirect another second later)
因此,它最终出现在一个没有原始端口的 URL 上,带有一个斜杠,并使用方案 https。
我能做些什么来解决它?
PS 如果尾部斜杠无关紧要(即localhost:8080/some_page 和localhost:8080/some_page/ 显示相同的内容。
PS 8080 端口只是我通过 Docker 在本地测试,它将容器 80 映射到主机 8080。
更新:
我已经实现了 Richard 的答案,并尝试了建议的 curl:
$ curl -I http://localhost:8080/some_page
HTTP/1.1 301 Moved Permanently
Server: nginx/1.21.4
Date: Thu, 09 Dec 2021 15:07:11 GMT
Content-Type: text/html
Content-Length: 169
Location: http://localhost/some_page/
Connection: keep-alive
请注意缺少 8080 端口。
更新 2:
使用 nginx 指令absolute_redirect off;,我得到了这个:
$ curl -I http://localhost:8080/some_page
HTTP/1.1 301 Moved Permanently
Server: nginx/1.21.4
Date: Thu, 09 Dec 2021 16:01:31 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Location: /some_page/
$ curl -I http://localhost:8080/some_page/
HTTP/1.1 404 Not Found
Server: nginx/1.21.4
Date: Thu, 09 Dec 2021 16:01:34 GMT
Content-Type: text/html
Content-Length: 153
Connection: keep-alive
所以,问题仍然是对/some_page/ 的请求如何提供来自/controller.php?p=some_page 的响应
【问题讨论】: