我在使用 NAT 的虚拟机中运行 nginx,当我从主机访问它时遇到重定向问题。
http://localhost:8080/test/index.htm
:有效。http://localhost:8080/test/
:有效。http://localhost:8080/test
:重定向到 http://localhost/test/
。这不是我想要的。 (注意它删除了端口号)
server_name_in_redirect off;
和
rewrite ^([^.]*[^/])$ $1/ permanent;
,但都没有成功。我的default.conf:
server {
listen 80;
server_name localhost;
# server_name_in_redirect off;
location / {
root /usr/share/nginx/html;
index index.html index.htm index.php;
}
location ~ \.php$ {
# rewrite ^([^.]*[^/])$ $1/ permanent;
root /usr/share/nginx/html;
try_files $uri =404;
#fastcgi_pass 127.0.0.1:9000;
fastcgi_pass unix:/tmp/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
上发布了此问题的可能解决方案;为了方便转载于此: 如果我正确理解了问题,您希望在请求针对
http://example.com/foo 时自动提供服务,而不使用 301 重定向http://example.com/foo/index.html 没有尾部斜线? 适合我的基本解决方案
服务器故障答案
try_files $uri $uri/index.html $uri/ =404;
第一个取自
$uri
- 与uri完全匹配
第二个$uri/index.html
- 匹配包含index.html的目录,其中路径的最后一个元素与该目录匹配 名称,尾部没有斜杠
第三个$uri/
- 与目录匹配
如果前面的模式都不匹配,则第四个=404
- 返回 404 错误页面。
server
块:
index index.html index.htm;
并将
try_files
修改为如下所示:
try_files $uri $uri/ =404;
它应该也能工作。
absolute_redirect off;
禁用绝对重定向,如下例所示:
server {
listen 80;
server_name localhost;
absolute_redirect off;
location /foo/ {
proxy_pass http://bar/;
}
如果我在
http://localhost:8080/foo
上运行curl,我可以看到重定向 HTTP 响应中的
Location
标头给出为 /foo/
而不是 http://localhost/foo/
。$ curl -I http://localhost:8080/foo
HTTP/1.1 301 Moved Permanently
Server: nginx/1.13.8
Date: Tue, 03 Apr 2018 20:13:28 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: /foo/
据此,我认为任何网络浏览器都会根据相对位置执行正确的操作。在 Chrome 上测试,效果很好。
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm index.php;
if (-d $request_filename) {
rewrite [^/]$ $scheme://$http_host$uri/ permanent;
}
}
}
server_name localhost;
# server_name_in_redirect off;
到
server_name localhost:8080;
server_name_in_redirect on;
$uri/
选项。请记住,带有
index
的文件夹中的默认文件具有正确的定义。例如:index index.html index.htm;
try_files $uri $uri/index.html $uri/ /index.html;
如果您需要在配置中维护
$uri/
,只需在
$uri/index.html
选项前添加$uri/
即可,需要先尝试索引。在此示例中,最后一个选项是显示 /index.html
的内容而不是
=404
错误对于像Docusaurus这样生成的静态页面很有用。