开发者

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 t开发者_高级运维o 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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜