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

为何我的Apache .htaccess中PHP文件拦截规则失效?

问题描述

我正在使用Apache服务器,配置了如下.htaccess文件:

<IfModule mod_deflate.c>
        SetOutputFilter DEFLATE
        AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml application/x-javascript
</IfModule>

<IfModule mod_headers.c>
  <FilesMatch "\.(bin|css|dae|jpeg|jpg|JPG|json|pdf|png|PNG|rb|scss|scssc|sh|styl|svg|swf|txt|vertex|xml|zf3d|zip)$">
    Header set Access-Control-Allow-Origin *
    Header append Access-Control-Allow-Credentials true
    Header append Cache-Control "max-age=86400, public"
  </FilesMatch>
</IfModule>

## EXPIRES CACHING ##
<IfModule mod_expires.c>
        ExpiresActive On
        ExpiresByType image/jpg "access 1 year"
        ExpiresByType image/jpeg "access 1 year"
        ExpiresByType image/gif "access 1 year"
        ExpiresByType image/png "access 1 year"
        ExpiresByType text/css "access 1 year"
        ExpiresByType text/html "access 1 year"
        ExpiresByType application/pdf "access 1 year"
        ExpiresByType text/x-javascript "access 1 year"
        ExpiresByType application/x-shockwave-flash "access 1 year"
        ExpiresByType image/x-icon "access 1 year"
        ExpiresDefault "access 1 year"
</IfModule>
## EXPIRES CACHING ##

<IfModule mod_mime.c>
        AddType application/vnd.ms-fontobject eot
        AddType font/opentype otf
        AddType font/otf otf
        AddType font/truetype ttf
        AddType font/ttf ttf
        AddType application/x-font-woff woff
        AddType application/font-woff woff
</IfModule>

<IfModule mod_rewrite.c>
        Options All -Indexes
        RewriteEngine on

        # Block PHP files in data folders
        RewriteRule ^(.*)/data/.*\.(php|php3|phtml)$ / [L,R=301]
        
        # Continues...
</IfModule>

但访问链接https://example.com/data/asd/bsd/aze66atsttza5652/test.php仍能成功访问,请问为何我的PHP文件拦截规则无法生效?

原因分析与解决方案

你的Rewrite规则失效的核心问题是匹配逻辑不符合目标URL结构:
当前规则^(.*)/data/.*\.(php|php3|phtml)$要求/data/前面必须存在任意字符,但你访问的URL是从根目录直接起始的/data/...,/data/前没有任何内容,导致规则匹配失败。

可以通过修改规则解决,以下两种写法任选其一:

  1. 允许/data/前为空,兼容根目录下的data文件夹:
RewriteRule ^(.*)?/data/.*\.(php|php3|phtml)$ / [L,R=301]
  1. 更简洁的写法,直接匹配以/data/开头的路径:
RewriteRule ^data/.*\.(php|php3|phtml)$ / [L,R=301]

额外检查项:

  • 确认Apache已启用mod_rewrite模块,Linux系统可执行a2enmod rewrite命令启用,之后重启Apache服务。
  • 确认网站虚拟主机配置中AllowOverride设置为All,否则.htaccess规则不会被解析。
  • 测试前清除浏览器缓存或使用无痕模式,避免旧响应缓存影响结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 21:55:55