I am using the following code to direct all www requests to non-www URLs:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.org$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]
This works great inside an .htaccess file in the root of my website.
For example,
www.example.com -> example.com/
www.example.com/ -> example.com/
www.example.com/other_page -> example.com/other_page
However, if I move this same code into my VirtualHost configuration, the rewritten URLs contain a double trailing slash.
www.example.com -> example.com//
www.example.com/ -> example.com//
www.example.com/other_page -> example.com//other_page
I fixed it by removing the slash from the rewrite rule:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.org$ [NC]
RewriteRule ^(.*)$ http://example.com$1 [R=301,L]
But I can't understand the reason for this. Anyone know why?
Best Answer
As I understand it, in .htaccess files, the string that mod_rewrite processes in your rule is relative to the directory the .htaccess file is in, so it will not have a / at the start.
In the VirtualHost entry, the string it processes is absolute to the root of the server, and so includes the /.
It makes for subtle differences in how mod_rewrite works.
Here is someone with a similar problem, and solution:
http://forum.modrewrite.com/viewtopic.php?p=56322&sid=77f72967f59200b5b5de174440234c3a
This should work in both cases, assuming I remember my escaping correctly: