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

如何在.htaccess中排除特定文件免受RedirectMatch 404规则限制?

问题:禁止访问隐藏文件/目录时如何排除指定文件

编辑:下方评论区的CBroe已给出解答

我正在加固www.mta-sts.[maindomain].com子域名,该子域名仅允许访问www.mta-sts.[maindomain].com/.well-known/mta-sts.txt这一个文件。我们希望禁止访问整个子域名下的所有隐藏文件和目录,但要将mta-sts.txt文件排除在该规则之外。

现有一条可正常禁止隐藏文件和目录的规则:

# deny access to hidden files and directories
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RedirectMatch 404 /\..*$ [L]

但尝试添加排除条件后无效,比如以下写法:

# deny access to hidden files and directories
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteCond %{REQUEST_URI} !^/.well-known/mta-sts\.txt$
RedirectMatch 404 /\..*$ [L]

正确解决方案

问题根源在于RedirectMatch属于mod_alias模块指令,不会受mod_rewrite模块的RewriteCond条件控制,二者分属不同模块,执行逻辑相互独立。需改用mod_rewrite的RewriteRule来实现,才能和RewriteCond配合生效。

修改后的规则如下:

# 禁止访问隐藏文件和目录,排除指定文件
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteCond %{REQUEST_URI} !^/.well-known/mta-sts\.txt$
RewriteRule ^\..*$ - [R=404,L]

规则说明

  • 前两个RewriteCond判断请求目标是真实存在的文件或目录
  • 第三个RewriteCond排除/.well-known/mta-sts.txt这个特定请求
  • RewriteRule匹配所有以.开头的路径(即隐藏文件/目录),返回404状态码并终止后续规则执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 00:06:25