使用mod_rewrite时要当心MultiViews

先看我遇到的问题:试图使用如下rewrite代码

RewriteEngine On RewriteBase /dex/ RewriteRule ^wsdl/(sjz|bd|qhd|common)/?$ wsdl.php?u=$1 [L] RewriteRule ^wsdl/?$ wsdl.php [L]

达到以下转换效果:

wsdl/sjz –> wsdl.php?u=sjz wsdl/ –> wsdl.php

但天不随人愿,第二行转换效果没问题,第一行转换效果总是出不来,查了一下RewriteLog,有一句引起了我的注意:

(1) pass through /dex/wsdl/sjz (3) [per-dir E:/cvswork/2005dex/] add path info postfix: E:/cvswork/2005dex/wsdl.php -> E:/cvswork/2005dex/wsdl.php/sjz

注意看第二句,它怎么把wsdl/sjz转换成了wsdl.php/sjz?难道和第二句RewriteRule有关?试着把第二句RewriteRule关掉,问题依旧。

于是祭起Google海搜,发现有人和我遇到了同样的问题

the problem lies in here somewhere with URL http://localhost/index/q we get:- add path-info postfix: c:/wwwroot/index.php -> c:/wwwroot/index.php/q strip per-dir prefix: c:/wwwroot/index.php/q -> index.php/q applying pattern ‘^([^/.]*)$’ to uri ‘index.php/q’ I dont want index.php/q though!!!!! argghhhhh!!! …… GOT IT!!!!!!! Bl**dy windows OS i removed the .htaccess file and http://localhost/phpinfo/x was still doing phpinfo.php I added a directory called phpinfo and it worked – giving a directory listing I re-created the .htaccess and voila it worked. So basically if a directory doesnt exist it looks for a script (.php .html) and then uses that with further parameters sdded to the end of it. I have to find a workaround for that now.

原来,是Apache在当前目录下找到了wsdl.php(依据wsdl/sjz中的wsdl),并且来了个狸猫换太子,继续搜索……终于在这个德语网页找到了答案:

MultiViews-option abschalten. wenn diese aktiviert ist, würde ein request nach /kategorie auch kategorie.php finden, und das kollidiert natürlich mit deiner RewriteRule, weil dort eben mit /kategorie/irgendwas ebenfalls ein “treffer” vorliegt – da kann der server also nicht entscheiden, was jetzt eigentlich gemeint ist.

上面是德语,我是看不懂的,用Google翻译如下:

MultiViews option switch off. if this is activated, after/category kategorie.php to also find request, and collides naturally with your RewriteRule, because evenly with/category/something is likewise present there a “hit” – there the server cannot decide thus, what is now actually meant.

原来是Apache的MultiViews选项干扰了RewriteRule,将其去掉之后,问题排除。

Options -MultiViews

继续寻找MultiViews的相关信息,收获如下:

所以,在没有明确需要的情况下,一般不要打开MultiViews选项,因为我们一般编写的程序很少用到它,反而会给正常的程序调试带来麻烦,另外早期的版本可能还存在一些安全问题。

在去掉MultiViews的同时,发现还有一个好像也没有用的Options——FollowSymLinks,但如果你的RewriteRule是写在.htaccess文件中的话,FollowSymLinks这个选项可不能去掉,去掉了RewriteEngine就不干活啦~~

Note To enable the rewriting engine for per-directory configuration files you need to set “RewriteEngine On” in these files and “Options FollowSymLinks” must be enabled. If your administrator has disabled override of FollowSymLinks for a user’s directory, then you cannot use the rewriting engine. This restriction is needed for security reasons.

Leave a Reply

Your email address will not be published. Required fields are marked *