You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker中Nginx移除URL的.html后缀时重定向丢失端口问题

Nginx移除.html后缀并重定向修复方案

问题原因

你的重定向存在两个核心问题:

  1. 缺失访问端口(8080):Nginx内部监听80端口,$host变量仅返回主机名(localhost),无法识别外部访问时的8080端口;
  2. 出现单斜杠(http:/localhost/index):是$host变量拼接时的隐式格式问题,改用包含完整Host信息的$http_host即可解决。

修复后的完整配置

替换原重定向规则,其余配置保持不变:

worker_processes 1;

events {
    worker_connections 1024;
}

http {
    include /etc/nginx/mime.types;
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;
    server {
        listen 80;
        server_name localhost;

        # 修复重定向逻辑:保留端口+修正格式
        location ~* ^/(.+)\.html$ {
            return 301 $scheme://$http_host/$1;
        }

        location / {
            root /usr/share/nginx/html;
            index index.html;
            try_files $uri $uri.html $uri/ =404;  
        }
        
        location /css {
            root /usr/share/nginx;
        }

        location /js {
            root /usr/share/nginx;
        }
    }
}

关键说明

  • $http_host:完整保留客户端请求中的Host头(含端口,如localhost:8080),适配Docker端口映射场景;
  • return 301:比rewrite指令更高效,直接返回永久重定向响应;
  • 正则^/(.+)\.html$:精准匹配所有带.html后缀的URL,捕获路径核心部分作为重定向目标。

内容的提问来源于stack exchange,提问作者Daniel López

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 14:49:53