使用.htaccess删除.php扩展名而不破坏DirectoryIndex

时间:2012-03-09 14:19:15

标签: .htaccess url-rewriting

我的.htaccess文件中有以下重写,它从文件中删除.php扩展名,例如将 so.com/question.php 转换为 so.com/question

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

然而,这也打破了默认的DirectoryIndex行为,其中只需键入目录将重定向到文件夹中的索引文件,例如 so.com/answer 显示 so.com/answer/index.php

简单地将上述代码与DirectoryIndex index.php结合起来并不能同时实现这两个结果。

有人可以帮我组合这两个函数,或者重写代码来排除index.php文件,这会得到相同的结果吗?

3 个答案:

答案 0 :(得分:25)

我认为你只需要在重写之前验证文件是否存在,这样你就可以保持404和directoryindex行为不变:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [NC,L]

(未经测试)

答案 1 :(得分:2)

RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [L, QSA]

验证文件和文件夹,并添加RewriteBase /

答案 2 :(得分:1)

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

我测试过,并且工作正常。