简体   繁体   中英

Apache vhost rewrite goes wrong with existing folders

I want my vhost to rewrite urls such as:
http://dev.example.com/cool/story/bro

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

Unless specifying an existing file such as:
http://dev.example.com/images/duck.png


It works fine but when I have a url which uses an existing folder such as:
http://dev.example.com/images

It strangely redirects to:
http://dev.example.com/images/?url=images

When it should rewrite to:
http://dev.example.com/index.php?url=images


Here's my current code:

<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>

I've been trying to fix it for hours but I can't see the problem, hope you can help.

You'll want to specify a RewriteCond for paths that are existing directories in addition to ones that are existing files.

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

I've come looking for a solution to this same problem, and @Chris Hendry's comment suggesting the rewrite log was very helpful in debugging this.

Not exactly, but you can have it log the rewrite actions to a log that you could follow. RewriteLog "/path/to/file/rewrite.log" RewriteLogLevel 3 httpd.apache.org/docs/2.2/mod/mod_rewrite.html#RewriteLogLevel – Chris Hendry

I traced the issue to Apache adding a trailing slash automatically whenever a folder is requested without it, as seen here: https://stackoverflow.com/questions/13354238#answer-13354276

Apache sees that a directory has been requested, and causes a 301 redirect to the "Correct" location.

The issue was fixed for me when I added this directive to my .htaccess file (in your case, it should work in the the vhost itself):

DirectorySlash Off

Edit: Make sure to clear your cache before testing again. The 301 redirect is cache.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM