5

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]
BrynJ
  • 8,322
  • 14
  • 65
  • 89
  • I am more curious just for learning purposes than anything else but what is the benefit of this redirect? – JM4 Feb 22 '11 at 16:34

2 Answers2

3

You could condense them into a single rule as well:

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

Mark's point about the / is an important consideration. Since you're defining the rule in .htaccess though, 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
  • 19,119
  • 6
  • 56
  • 66
2

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).