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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM