在.htaccess中将DirectoryIndex优先化为RewriteRule

时间:2016-02-03 14:51:11

标签: apache .htaccess

我想要在DirectoryIndex行中指定的文件可用时访问它们。例如。当有人在www.mywebsite.com/mydir/中输入时,它会正确重定向。为此,我在.htaccess中有这一行:

DirectoryIndex index.html default.php 

当文件名或目录不存在时,我希望它重定向到与我的.htaccess文件位于同一目录中的文件(target_handler.php)。为此我在DirectoryIndex之后放了几行:

RewriteEngine On
RewriteCond %{ENV:URI} ^$
RewriteRule ^(.*)$ - [ENV=URI:$1]

RewriteCond %{ENV:BASE} ^$
RewriteCond %{ENV:URI}::%{REQUEST_URI} ^(.*)::(.*?)\1$
RewriteRule ^ - [ENV=BASE:%2]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ %{ENV:BASE}target_handler.php [L,QSA]

我想要的是Apache首先检查是否有index.html或default.php可用,并且只有在不可用时执行重写。目前行为似乎是随机的(?),所以如果有人输入www.mywebsite.com/mydir/,那么Apache有时会先进行重写而不检查指定文件夹中是否有index.html。

帮助表示赞赏

PS:我正在测试使用:xampp Apache / 2.4.17(Win32)OpenSSL / 1.0.2d PHP / 5.6.15

1 个答案:

答案 0 :(得分:0)

您可以省略DirectoryIndex并使用mod_rewrite本身完成所有操作:

RewriteEngine On

RewriteCond %{REQUEST_URI}::$1 ^(.*?/)(.*)::\2$
RewriteRule ^(.*)$ - [E=BASE:%1]

RewriteCond %{DOCUMENT_ROOT}%{ENV:BASE}index\.html -f
RewriteRule ^ index.html [L]

RewriteCond %{DOCUMENT_ROOT}%{ENV:BASE}default\.php -f
RewriteRule ^ default.php [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !^target_handler\.php$ target_handler.php [L,NC]
相关问题