Url 如果存在';没有尾随斜杠
我使用NAT在虚拟机中运行nginx,从主机访问nginx时出现重定向问题 工作如期进行Url 如果存在';没有尾随斜杠,url,redirect,nginx,Url,Redirect,Nginx,我使用NAT在虚拟机中运行nginx,从主机访问nginx时出现重定向问题 工作如期进行 http://localhost:8080/test/index.htm:工作正常 http://localhost:8080/test/:工作正常 没有按预期工作 http://localhost:8080/test:重定向到http://localhost/test/。这不是我想要的(注意它会去掉端口号) 我试过的 根据我在谷歌上搜索的内容,我尝试了server\u name\u in\u re
:工作正常http://localhost:8080/test/index.htm
:工作正常http://localhost:8080/test/
:重定向到http://localhost:8080/test
。这不是我想要的(注意它会去掉端口号)http://localhost/test/
server\u name\u in\u redirect off代码>和重写^([^.]*[^/])$$1/永久代码>,两者都没有成功
我的default.conf:
试着改变
server_name localhost;
# server_name_in_redirect off;
到
尝试:
我在上发布了这个问题的可能解决方案;为方便起见,此处复制:
如果我理解正确的话,当请求没有尾部斜杠时,您希望在不使用301重定向的情况下自动提供服务吗
适合我的基本解决方案
如果是这样,我发现这个try_文件配置可以工作:
try_files $uri $uri/index.html $uri/ =404;
- 第一个
$uri
与uri完全匹配
- 第二个
$uri/index.html
匹配包含index.html的目录,其中路径的最后一个元素与该目录匹配
名称,不带尾随斜杠
- 第三个
$uri/
与目录匹配
- 如果前面的模式都不匹配,则第四个
=404
返回404错误页面
取自
我的更新版本
如果在服务器
块中添加:
index index.html index.htm;
并将try_files
修改为如下所示:
try_files $uri $uri/ =404;
它应该也能工作。一个比较简单的解决方案,对我有效,就是禁用绝对重定向,同时关闭absolute\u redirect代码>如下例所示:
server {
listen 80;
server_name localhost;
absolute_redirect off;
location /foo/ {
proxy_pass http://bar/;
}
如果我在http://localhost:8080/foo
,我可以看到重定向HTTP响应中的位置
头被指定为/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上测试,效果很好。@maiconsanson-它似乎适用于我的子文件夹。请随意进一步解释。对不起,我的意思是,它可以工作,但是找不到index.html中的图像。顺便说一句,我用Dokku来解决这个问题:if(-d$request_filename){rewrite[^/]$$scheme://$http\u host$uri/permanent;}
index.html中的相对路径可能会以某种方式被破坏。检查页面试图检索的url,并与图像实际所在的url进行比较,看看问题是否变得更清楚。url正常(1.png
等等)。所有内容都在根应用程序中(index.html和图像)。Upvote++用于try_文件$uri$uri/index.html$uri/=404;逻辑!它起作用了,感谢这仍然返回了301。这里有一个问题的解释和一个实际的解决方案:根据我的理解,这个问题实际上并不是在抱怨301本身。301很好,问题是重定向应该指向保持端口8080的相同服务器名。这对我来说很好。对于额外的偏执狂,您可以将absolute_redirect off
的作用域设置为位置{}
块,如果您只需要该位置
try_files $uri $uri/ =404;
server {
listen 80;
server_name localhost;
absolute_redirect off;
location /foo/ {
proxy_pass http://bar/;
}
$ 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/