在访问带目录的URL时,如果末尾不加斜杠(“/”),Nginx默认会自动加上,其实是返回了一个301跳转,在新的Location中加了斜杠。
但这个默认行为在Nginx前端有LB负载均衡器、且LB的端口与Nginx Server监听的端口不同时,可能会导致访问出错。
比如域名所指向的LB对外监听端口80,转发到后端Nginx 8080端口,当Nginx进行上述自动重定向时,导致重定向到了域名的8080端口,如:
$ curl -I http://www.mydomain.com/app HTTP/1.1 301 Moved Permanently Date: Tue, 21 Nov 2017 08:27:50 GMT Content-Type: text/html Content-Length: 178 Connection: keep-alive Server: nginx Location: http://www.mydomain.com:8080/app/ (这里由于LB没有监听8080端口,导致访问出错)
此时,解决方法有两种。
1)新版本nginx(≥1.11.8)可以通过设置 absolute_redirect off; 来解决:
server { listen 8080; server_name www.mydomain.com; absolute_redirect off; #取消绝对路径的重定向 root html; ... }
即使用相对路径的重定向,结果如下:
$ curl -I http://www.mydomain.com/app HTTP/1.1 301 Moved Permanently Date: Tue, 21 Nov 2017 07:45:21 GMT Content-Type: text/html Content-Length: 178 Connection: keep-alive Server: nginx Location: /app/ (这里变成了相对路径)
2)LB是80端口的,旧版本nginx(<1.11.8)可以增加 port_in_redirect off; 参数来解决:
server { listen 8080; server_name www.mydomain.com; #absolute_redirect off; # appeared in version 1.11.8 port_in_redirect off; ... }
即去掉重定向后的Location中的端口,效果如下:
$ curl -I http://www.mydomain.com/app HTTP/1.1 301 Moved Permanently Date: Tue, 21 Nov 2017 13:03:34 GMT Content-Type: text/html Content-Length: 178 Connection: keep-alive Server: nginx Location: http://www.mydomain.com/app/
如果LB监听非80端口,那建议升级Nginx到1.11.8版本以上了。