.htaccess如何捕获网站根目录默认索引请求?
解决.htaccess捕获根目录默认PHP索引的重定向问题
问题场景
我在网站根目录放置了.htaccess文件,需要将所有PHP页面重定向至/notice.php,且重定向仅在特定时间生效。现有规则对https://www.website.com/index.php这类带文件名的PHP请求有效,但访问根目录https://www.website.com/(默认索引为index.php)时无法触发重定向,仍会显示index.php内容。
试过的无效规则包括:
RewriteCond %{REQUEST_URI} !/notice.php$ RewriteCond %{REQUEST_FILENAME} \.php$ [OR] RewriteCond %{REQUEST_FILENAME} ^/$ RewriteRule $ /notice.php [R,L]
以及:
RewriteCond %{REQUEST_URI} !/notice.php$ RewriteCond %{REQUEST_FILENAME} \.php$ [OR] RewriteCond %{REQUEST_FILENAME} ^.*$ RewriteRule $ /notice.php [R,L]
由于重定向有时间敏感性,不能直接使用DirectoryIndex notice.php,需要保留时间条件(示例为%{TIME} >=20241130230000)。
原因分析
访问根目录/时,%{REQUEST_FILENAME}指向的是服务器上的目录路径(而非index.php文件),因此原规则中针对.php文件的条件无法匹配;同时%{REQUEST_FILENAME} ^/$也不成立,因为它实际是目录的物理路径(比如/var/www/html/),不是字符串/。
解决方案
方法1:结合默认索引文件的存在性检查
通过判断根目录请求+默认索引文件存在的情况,覆盖根目录场景:
RewriteEngine On # 时间条件:仅在2024-11-30 23:00之后生效 RewriteCond %{TIME} >=20241130230000 # 排除目标页面notice.php,避免循环重定向 RewriteCond %{REQUEST_URI} !/notice.php$ # 匹配两种情况:1. 直接请求PHP文件;2. 请求根目录且默认index.php存在 RewriteCond %{REQUEST_FILENAME} \.php$ [OR] RewriteCond %{REQUEST_URI} ^/$ RewriteCond %{DOCUMENT_ROOT}/index.php -f RewriteRule ^ /notice.php [R,L]
方法2:利用%{THE_REQUEST}捕获原始请求
%{THE_REQUEST}记录的是浏览器发送的原始请求行,不受内部重写影响,能更准确判断请求目标:
RewriteEngine On RewriteCond %{TIME} >=20241130230000 # 排除notice.php的请求 RewriteCond %{THE_REQUEST} !/notice.php # 匹配直接请求PHP文件,或者根目录请求(对应默认index.php) RewriteCond %{THE_REQUEST} ^GET\ /(.*\.php|)\ HTTP/ RewriteRule ^ /notice.php [R,L]
两种方法都能同时覆盖带文件名的PHP页面和根目录默认索引的重定向需求,且保留了时间敏感性条件。
内容的提问来源于stack exchange,提问作者Mm-Art-In
相关产品推荐
相关产品推荐

