Nginx环境301跳转去掉index.html的方法

我们在有些场景中看到跳转的URL地址中包括index.html,这里我们要去掉隐藏,如何实现?

1、将所有包含index.html的URL永久重定向到干净路径

server {
    listen 80;
    server_name domain.com;
    
    # 核心重定向规则(去除index.html)
    if ($request_uri ~* "/index\.html$") {
        rewrite ^(.*)/index\.html$ $1 permanent;
    }
    
    # 其他原有配置...
}

permanent 表示301永久重定向

正则表达式 ^(.*)/index\.html$ 会匹配所有以/index.html结尾的URL

2、同时处理index.html和斜杠结尾的规范化

/path/index.html → /path/

/path → /path/)

server {
    listen 80;
    server_name domain.com;
    
    # 规则1:去除index.html并补全斜杠
    rewrite ^/(.*)/index\.html$ /$1/ permanent;
    
    # 规则2:为不含斜杠的目录请求补全斜杠
    rewrite ^/([^.?]+[^.?/])$ /$1/ permanent;
    
    # 其他原有配置...
}

 

投上你的一票

原创文章,转载请注明出处:https://www.itbulu.com/nginx-remove-html.html

上一篇 2025年4月7日 13:02
下一篇 2025年4月17日 15:09