nginx多层代理转发后,浏览器地址自动加上斜杠/并且端口错误问题
问题出现的情况:
比如一个前端web应用部署在内网 http://2.2.2.2:8082/web 上,但是2.2.2.2无法直接在外网访问,需要另一个dmz服务器1.1.1.1做一层代理转发。dmz服务器1.1.1.1的82端口映射到公网ip的18082端口上从而通过在公网上访问18082进入web应用。
整个链路为:
公网IP:18082 >>nat映射>> dmz服务器 1.1.1.1:82 >>nginx代理>> 内网服务器2.2.2.2:8082
则示例nginx.conf如下
内网2.2.2.2的nginx.conf
server {
listen 8082;
server_name localhost;
location /web {
alias /somewebpath;
try_files $uri $uri/ /web/index.html;
index index.html index.htm;
}
}
dmz服务器1.1.1.1的代理转发nginx.conf
server {
listen 82;
server_name localhost;
location / {
proxy_pass http://2.2.2.2;
}
}
问题描述
公网浏览器访问 http://公网ip:18082/web 时无法正常打开,使用开发者工具查看,可以发现http://公网ip:18082/web返回了一个301重定向301 Moved Permanently,重定向地址是http://公网ip:82/web,因为公网ip的82端口并没有开,所以无法打开。
这是因为nginx会自动给不带/的地址补上/,这是基于前一级地址作为绝对路径,通过301重定向实现的。
解决方法
给实际提供web包的nginx加上absolute_redirect off,这个语句要求nginx版本高于1.11.8
内网2.2.2.2的nginx.conf
server {
listen 8082;
server_name localhost;
location /web {
absolute_redirect off;
alias /somewebpath;
try_files $uri $uri/ /web/index.html;
index index.html index.htm;
}
}
参考 https://www.jianshu.com/p/c1a41fc9a5cc