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

如何修改.htaccess阻止子文件夹URL末尾自动添加/的301重定向

解决方案

要实现x.com/example直接返回/example/index.html内容且不触发重定向,需要修改两处规则:

  1. 关闭Apache默认的目录斜杠自动重定向
  2. 添加规则处理不带斜杠的目录请求

修改后的完整.htaccess代码如下:

RewriteEngine On
DirectorySlash Off

# 禁用HTTP
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# 移除www前缀
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

# /random 对应执行 random.php
RewriteCond %{REQUEST_FILENAME}!-f
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

# 处理不带斜杠的目录请求,直接加载index.html
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME}/index.html -f
RewriteRule ^(.*[^/])$ $1/index.html [L]

# 将URL中的/index.html重定向到/
RewriteRule (.*)index\.html$ /$1 [R=301,L]

# 将URL中的xxx.html重定向到xxx
RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]

修改说明:

  • DirectorySlash Off:关闭Apache默认行为——当访问不带结尾斜杠的目录时,自动发送301重定向到带斜杠的版本。
  • 新增的目录处理规则:
    • RewriteCond %{REQUEST_FILENAME} -d:判断当前请求的路径是真实存在的目录
    • RewriteCond %{REQUEST_FILENAME}/index.html -f:判断该目录下存在index.html文件
    • RewriteRule ^(.*[^/])$ $1/index.html [L]:内部重写请求到目录下的index.html,[L]标记停止后续规则处理,URL地址保持不变。

内容的提问来源于stack exchange,提问作者user3422533

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 00:40:05