APACHE – mod_rewrite creates 301 instead of transparent redirection if folder exists – efreedom
APACHE – mod_rewrite creates 301 instead of transparent redirection if folder exists
Hello, i’m having a small problem here. I’m using a simple rule to redirect all requests to a script, excepts some folders with static content :
RewriteEngine On
RewriteCond $1 !^(templates|css|js|uploads)/(.*)$
RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]
Most of the time, the redirection is good and transparent. But if the folder matching the URL exists and if i don’t put the last « / », i will have a 301 redirect.
Examples : (the folder gallery doesn’t exists but mods does)
* ht*p://localhost/test/gallery/ -> OK
* ht*p://localhost/test/mods/ -> OK
* ht*p://localhost/test/mods -> 301 redirection to ht*p://localhost/test/mods/?url=mods
I have this problem on all apache2 servers (tested Fedora, Debian, Windows).
Someone knows how to solve this ? Thanks
This question and answers originated from stackoverflow.com
Question by Ugo Méda
Answer
This is due to the DirectorySlash directive, which will perform the external redirection after your rewrite is performed, which has the unintended consequence of taking your added query string with it.
You can turn DirectorySlash off, but it’s not recommended for the reasons described in the documentation. The preferred option in this case is probably to just perform mod_dir’s work for it, redirecting to the appropriate slash-terminated URL before performing your rules. Something like this above your existing rule should work:
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_URI} !/$
RewriteRule ^.*$ /$0/ [R=301,L]
viaAPACHE – mod_rewrite creates 301 instead of transparent redirection if folder exists – efreedom.