views:

424

answers:

1

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

I'm using the following, but getting 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]
+2  A: 

In your existing rules you appear to have some stuff the wrong way around, and I don't think there's any need for the negative (i.e. !) test.

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

However I'd suggest that you don't use the RewriteCond directive to check the hostname, just make sure the rule is in the right 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 that blog.example.com and www.example.com are actually separate virtual hosts)

Alnitak