Rewrite the URL from http://example.com/blog/ to http://blog.example.com/

What should the RewriteRule (using .htaccess / mod_rewrite ) be used to redirect http://example.com/blog/ (with www or without www ) to http://blog.example.com/ ?

I use the following, but get a redirect loop:

 RewriteEngine On RewriteCond %{HTTP_HOST} !^www\.example\.com [NC] RewriteRule ^(.*)$ http://www.example.com/blog/ [L,R=301] RewriteCond %{HTTP_HOST} www\.example\.com [NC] RewriteRule ^(.*)$ http://www.example.com/blog/ [L,R=301] 
+4
source share
1 answer

There seems to be something wrong with your existing rules, and I don't think there is a need for a negative (i.e. ! ) Test.

 RewriteEngine On RewriteCond %{HTTP_HOST} ^(www\.)?example\.com [NC] RewriteRule ^/blog/$ http://blog.example.com/ [L,R=301] 

However, I would suggest that you do not use the RewriteCond directive to verify the host name, just make sure the rule is in the correct VirtualHost for www.example.com .

 <VirtualHost ...> ServerName www.example.com ServerAlias example.com RewriteRule ^/blog/ http://blog.example.com/ [L,R=301] </VirtualHost> 

(nb: assumes blog.example.com and www.example.com are actually separate virtual hosts)

+6
source

All Articles