如何在.htaccess中配置阻止所有.php文件并添加指定访问例外?
解决.htaccess中PHP文件访问限制的例外配置问题
需求:访问者尝试访问.php格式URL时跳转至自定义404错误页面,但需给特定路径的PHP文件(如maybe-something/allowed-file.php)设置访问例外。
当前已有的.htaccess配置如下:
ErrorDocument 404 /error404.php ErrorDocument 403 /error404.php Options -MultiViews RewriteEngine on RewriteCond %{SERVER_PORT} 80 # Force WWW & SSL RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule (.*) https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301] ##.php envia a 404 RewriteCond %{ENV:REDIRECT_STATUS} ^$ RewriteRule ^(.+)\.php - [F,L]
修改方案
要添加多个例外,只需在阻止PHP文件的规则前,添加否定匹配的RewriteCond条件,排除你允许访问的PHP文件路径即可。
1. 逐个添加例外(适合少量规则)
如果例外数量不多,可以逐个添加条件,用OR连接多个规则(最后一个条件不需要OR参数):
##.php envia a 404 - 先排除允许的PHP文件 RewriteCond %{ENV:REDIRECT_STATUS} ^$ # 允许根目录下的allowed-file.php访问 RewriteCond %{REQUEST_URI} !^/allowed-file\.php$ [NC] # 允许maybe-something目录下的allowed-file.php访问,添加OR参数连接下一个规则 RewriteCond %{REQUEST_URI} !^/maybe-something/allowed-file\.php$ [NC,OR] # 允许another-path目录下的another-file.php访问 RewriteCond %{REQUEST_URI} !^/another-path/another-file\.php$ [NC] # 阻止其他所有PHP文件访问 RewriteRule ^(.+)\.php - [F,L]
2. 批量合并例外(适合大量规则)
如果需要放行数十个例外,可以把所有允许的路径合并到一个正则表达式中,简化代码:
##.php envia a 404 - 批量排除允许的PHP文件 RewriteCond %{ENV:REDIRECT_STATUS} ^$ # 用|分隔所有允许的路径,括号包裹匹配组 RewriteCond %{REQUEST_URI} !^/(allowed-file\.php|maybe-something/allowed-file\.php|another-path/another-file\.php|more-paths/allow-this\.php)$ [NC] RewriteRule ^(.+)\.php - [F,L]
关键参数说明
!:表示否定匹配,即当请求路径不匹配规则时,才执行后续的阻止规则[NC]:不区分大小写,确保Allowed-File.PHP这类大小写混合的路径也能被正确放行^和$:锚定路径的开头和结尾,避免部分匹配导致误判(比如防止allowed-file.php.bak这类非目标文件被意外放行)
修改后的完整配置
整合所有规则后的最终.htaccess代码如下:
ErrorDocument 404 /error404.php ErrorDocument 403 /error404.php Options -MultiViews RewriteEngine on # Force WWW & SSL RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule (.*) https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301] ##.php envia a 404 - 带例外配置 RewriteCond %{ENV:REDIRECT_STATUS} ^$ RewriteCond %{REQUEST_URI} !^/(allowed-file\.php|maybe-something/allowed-file\.php|another-path/another-file\.php)$ [NC] RewriteRule ^(.+)\.php - [F,L]
内容的提问来源于stack exchange,提问作者algoepico
相关产品推荐
相关产品推荐

