views:

32

answers:

2

I need to redirect from a main domain like mydomain.com or www.mydomain.com to sub.mydomain.com - and this needs to work for all requests, so mydomain.com/whatever goes to sub.mydomain.com/whatever.

I've tried this, which only works for non-www at the main domain:

RewriteCond %{HTTP_HOST} ^mydomain.com [NC]
RewriteRule ^(.*)$ http://sub.mydomain.com/$1 [L,R=301]
+1  A: 

Also add:

RewriteCond %{HTTP_HOST} ^www\.mydomain.com\.com$ [NC]
RewriteRule ^(.*)$ http://sub.mydomain.com$1 [R=301,L]

One thing also to note is you likely don't want that last / in your RewriteRule, as it'll add two slashes to the redirected URL (e.g. http://mydomain.com/foo.html becomes http://sub.mydomain.com//foo.html).

Mark Trapp
+1  A: 

You could condense them into a single rule as well:

RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewruteRule ^ http://sub.example.com%{REQUEST_URI} [R=301,L]

Mark's point about the / is an important consideration, but since you're defining the rule in .htaccess, the input (and by association the captured backreference) will not start with a leading slash, so you actually do need an explicit one in this case (like you had).

Since we just want the whole path anyway, using %{REQUEST_URI} is more reliable in this sense because it will always have a leading slash, regardless of the context we're using the rule in.

Tim Stone