Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

301 Redirect from main domain (www and non-www) to subdomain

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]
like image 869
BrynJ Avatar asked Aug 20 '10 19:08

BrynJ


1 Answers

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.

like image 177
Tim Stone Avatar answered Sep 23 '22 13:09

Tim Stone