Apache vhost重写现有文件夹出错


Apache vhost rewrite goes wrong with existing folders

我希望我的vhost重写url,如:
http://dev.example.com/cool/story/bro

:
http://dev.example.com/index.php?url=cool/story/bro

除非指定已存在的文件,例如:
http://dev.example.com/images/duck.png


它工作得很好,但是当我有一个使用现有文件夹的url时,例如:
http://dev.example.com/images

它奇怪地重定向到:
http://dev.example.com/images/?url=images

当它应该重写为:
http://dev.example.com/index.php?url=images


下面是我当前的代码:

<VirtualHost *:80>
        ServerName dev.example.com
        DocumentRoot /var/www/dev/public
        php_flag display_errors 1
        php_value error_reporting 30719
        <Directory "/var/www/dev/public">
                RewriteBase /
                RewriteEngine On
                RewriteCond %{REQUEST_FILENAME} !-f
                RewriteRule ^(.*)$ index.php?url=$1 [L]
        </Directory>
</VirtualHost>

我已经试了好几个小时了,但还是看不出问题所在,希望你能帮忙。

除了现有文件之外,您还需要为现有目录指定一个RewriteCond。

RewriteBase /
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)$ index.php?url=$1 [L]

我一直在寻找同样问题的解决方案,@Chris Hendry的评论建议重写日志对调试非常有帮助。

不完全正确,但是您可以让它将重写操作记录到您可以遵循的日志中。RewriteLog "/path/to/file/rewrite.log" RewriteLogLevel 3 httpd.apache.org/docs/2.2/mod/mod_rewrite.html#RewriteLogLevel - Chris Hendry

我跟踪这个问题到Apache在请求一个文件夹时自动添加一个斜杠,如下所示:https://stackoverflow.com/questions/13354238#answer-13354276

Apache看到一个目录已经被请求,并导致301重定向到"正确"位置。

当我将这个指令添加到我的。htaccess文件时(在你的情况下,它应该在vhost本身中工作),这个问题被修复了:

DirectorySlash Off

编辑:确保在再次测试之前清除缓存。301重定向是缓存