nginx 跳转用了内部端口问题,内部端口为非标准端口,try_file内部跳转

问题:

前端在nginx发布静态页面,格式是"文件夹/index.html",这里的例子为:test1/index.html

正常端口(80,443)的nginx是没有任何问题,非正常端口(我是88,但是我对外的访问端口是https 443,想当于做了端口转发吧),就有问题了

这是主要问题:访问https://liang.royole.com/test1   跳转为---> https://liang.royole.com:88/test1/   然后报错

一. 分析问题:

1 谷歌浏览器F12:(301重定向很快,记得勾选preserve log保留日志)

发现https://liang.royole.com/test1 跳转到https://liang.royole.com:88/test1/  然后对外没有88这个端口就报错

2.  分析为啥会跳转

nginx配置文件查看:

--------------------------------------------------------------------------------------

server {
listen 88 ;
server_name liang.royole.com;

#静态页面地址
location / {
root /web;
index index.html;
try_files $uri $uri/ /index.html; 
} }

 --------------------------------------------------------------------------------------

原来是try_files搞的鬼,意思是浏览器访问https://liang.royole.com/test1  尝试找“文件”(注意是文件不是文件夹),

发现没有test1文件,然后找文件夹test1,如果都没找到,最后找根/index.html;

问题就出在:发现没有test1这个“文件”的时候,跳转找test1文件夹;很开心初步定位到问题!

3. 分析为啥跳转后会带上了88端口 (https://blog.51cto.com/tongcheng/1427194

因为try_files 默认实现的是内部跳转,就是拿了server_name+listen拼接$uri;所以才会有了88端口的出现

二. 解决问题

解决问题的关键就是 try_files跳转的时候 用浏览器的域名和端口

添加下面这个判断:

#判断请求如果是文件夹,则重定向用浏览器地址端口和后缀,如果不判断,则内部跳转拿了listen81的端口
#$http_host意思是拿到浏览器的域名和端口
if (-d $request_filename) {
 rewrite [^/]$ $scheme://$http_host$uri/ permanent;
}

完整添加:

server {
listen 88 ;
server_name liang.royole.com;

#静态页面地址
location / {

if (-d $request_filename) {
 rewrite [^/]$ $scheme://$http_host$uri/ permanent;
}
root /web;
index index.html;
try_files $uri $uri/ /index.html; 
} }

一些参考文章

https://www.cnblogs.com/faberbeta/p/nginx008.html

https://my.oschina.net/abcfy2/blog/532041

https://stackoverflow.com/questions/50236411/nginx-localhost-port-is-lost-when-clicking-on-anchor-links

https://blog.51cto.com/tongcheng/1427194

原文地址:https://www.cnblogs.com/thirteen-yang/p/14134211.html