我需要.htaccess文件允许所有文件和目录(如果存在),但现有文件不需要php扩展,其他所有内容都转到索引文件。(MVC类型处理)我尝试了一些事情,但避风港尚未解决。
实例:
www.example.com/search/
文件以search.php存在,应显示文件
www.example.com/shopping/mylist/
文件不存在所以应该去index.php
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ $1.php [L]
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
答案 0 :(得分:1)
mod_rewrite是高度依赖于顺序的,所以让我们从最具体到最不具体的逻辑思考。
您需要一个条件来首先根据.php
中()
组的匹配来检查RewriteCond
文件是否存在。这将是两个条件,后跟RewriteRule
实际将其引导到.php
文件中。您的示例/search/
有一个斜杠,这就是为什么我们首先需要将%1
捕获为两个RewriteCond
。否则,我可能会使用%{REQUEST_FILENAME}.php -f
来测试它是否存在。 This sort of explains如何在%1
链中使用RewriteCond
反向引用。
然后在应用那个尝试匹配.php
文件之后,使用您已经拥有的更通用的index.php
规则,以及检查文件是否确实存在的两个条件。< / p>
RewriteEngine On
# Match an optional trailing slash on the filename
# and capture it as %1
RewriteCond %{REQUEST_FILENAME} ^(.+)/?
# And test if the match (without /) has a .php file
RewriteCond %1.php -f
# Rewrite everything up to an optional trailing /
# matched in the first RewriteCond
# into its .php suffix (add QSA to retain query string)
# It isn't necessary to give a full regex here since %1
# already contains everything needed
RewriteRule ^ %1.php [L,QSA]
# Now with that out of the way, apply the generic
# rule to rewrite any other non-existing file to index.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
# I used * instead of + so it also matches an empty url
RewriteRule ^(.*) index.php?url=$1 [QSA,L]
我已在临时目录中成功测试了此设置。它似乎符合您的要求。