Mod rewrite 协助.htaccess

Mod rewrite 协助.htaccess,mod-rewrite,Mod Rewrite,我需要.htaccess文件来允许所有文件和目录(如果它们存在的话),但是现有文件不需要php扩展名,其他所有内容都转到索引文件。(MVC类型处理)我已经尝试了一些方法,但还没有完全正确。 示例: www.example.com/search/ 文件以search.php形式存在,应显示该文件 www.example.com/shopping/mylist/文件不存在,因此应转到index.php RewriteEngine on RewriteCond %{REQUEST_FILENAME}

我需要.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]

mod_rewrite是高度顺序依赖的,所以让我们从最具体到最不具体的逻辑角度来考虑它

首先,您需要一个条件,根据
RewriteCond
()
组的匹配来检查
.php
文件是否存在。这将是两个条件,后跟一个
重写规则
,将其实际导入
.php
文件。您的示例
/search/
后面有一个斜杠,这就是为什么我们首先需要用两个
RewriteCond
将其捕获为
%1
。否则,我可能会使用
%{REQUEST_FILENAME}.php-f
来测试它是否存在。如何在
RewriteCond
链中使用
%1
反向引用

然后,在应用该规则尝试匹配
.php
文件后,使用更通用的
index.php
规则以及两个条件来检查文件是否实际存在

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]
我已在临时目录中成功测试了此设置。它似乎符合您的要求