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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With