URL 结尾不带斜杠时,重定向地址带有端口

发布于 2024-04-04  199 次阅读


问题描述

nginx 中配置如下 location 规则:

location /demo/ {
    proxy_pass http://localhost:8000/demo/;
}

server 块监听 8080 端口

此时访问 /demo/ 路径,返回正常;而访问 /demo 时,被 301 重定向到 域名:8080/demo/

即便配置了:

location /demo {
    rewrite ^/demo$ /demo/ permanent;
}

依然没用。

解决方法

实际上如此配置时,当请求 URL 后面没有 / ,Nginx 目录中没有对应的文件,就会自动进行 301 并在末尾加上 /,且默认配置中是带有 port_in_redirect on;absolute_redirect on;,所以重定向 URL 多了端口号。

所以要解决这个问题,只要在配置中添加 port_in_redirect off;,如果是 Nginx 版本号大于 1.11.8,可以考虑用 absolute_redirect off;

此外也不用额外写一个末尾不带 / 的重定向配置了。