mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4mobile wallpaper 5mobile wallpaper 6
603 字
2 分钟
🔧 Nginx 301 重定向暴露端口号问题解决方案
2025-12-06

🔧 Nginx 301 重定向暴露端口号问题解决方案#

💡 问题描述: 当客户端通过 API 网关或反向代理访问后端 Nginx 服务时,Nginx 在处理目录访问(缺少尾部斜杠)时会自动返回 301 重定向。重定向的 Location 头可能会暴露 Nginx 的内部端口号,导致客户端请求失败。

核心解决方案是在 Nginx 的 server 块中配置 absolute_redirect off;,禁用绝对路径重定向。


问题场景#

典型的问题场景如下:

  • 客户端通过 API 网关(如 https://blog.gmai.top,监听 443 端口)访问后端服务
  • 后端 Nginx 监听在内部端口(如 8080、50001 等)
  • 当访问的路径是目录且缺少尾部斜杠时(如 /hd-portal),Nginx 会自动返回 301 重定向到 /hd-portal/
  • 问题: 重定向的 Location 头暴露了 Nginx 的内部端口号,如 https://blog.gmai.top:50001/hd-portal/
  • 导致客户端无法正确访问,请求链断裂

原因分析#

Nginx 在遇到目录访问时,会根据以下配置参数生成 301 重定向响应:

  • absolute_redirect:是否启用绝对路径重定向(默认 on
  • server_name_in_redirect:重定向中是否使用 server_name(默认 off
  • port_in_redirect:重定向中是否包含端口号(默认 on

absolute_redirecton 时,Nginx 会生成包含完整 URL 的 Location 头,可能会包含内部端口号,从而暴露给客户端。


解决方案:配置 absolute_redirect off#

在 Nginx 的 server 块中添加 absolute_redirect off; 配置,禁用绝对路径重定向。

配置示例#

server {
listen 8080;
server_name blog.gmai.top;
# 禁用绝对路径重定向
absolute_redirect off;
location / {
root /var/www/html;
index index.html index.htm;
}
location /hd-portal {
alias /var/www/hd-portal;
index index.html;
}
}

配置说明#

  • absolute_redirect off;:禁用绝对路径重定向,Nginx 将返回相对路径的 Location 头(如 /hd-portal/),而不是完整的 URL(如 https://blog.gmai.top:50001/hd-portal/
  • 配置应放置在 server中,对整个虚拟主机生效
  • 如果只需要对特定 location 生效,也可以放置在 location 块中

重新加载 Nginx 配置#

修改配置后,重新加载 Nginx 使配置生效:

# 测试配置文件语法
sudo nginx -t
# 重新加载配置
sudo nginx -s reload
# 或
sudo systemctl reload nginx

验证效果#

使用 curl 命令验证重定向行为:

# 访问目录(缺少尾部斜杠)
curl -I https://blog.gmai.top/hd-portal
# 预期响应(配置前)
HTTP/1.1 301 Moved Permanently
Location: https://blog.gmai.top:50001/hd-portal/
# 预期响应(配置后)
HTTP/1.1 301 Moved Permanently
Location: /hd-portal/

配置后,Location 头变为相对路径,不再暴露内部端口号。


总结#

通过在 Nginx 的 server 块中配置 absolute_redirect off;,可以有效解决 301 重定向暴露内部端口号的问题,确保客户端请求正常转发,避免暴露服务器内部架构信息。

关键配置:

server {
server_name blog.gmai.top;
absolute_redirect off;
}

部分信息可能已经过时