301从主域(www和非www)重定向到子域
我需要从 mydomain.com 或 www.mydomain.com 等主域重定向到 sub.mydomain.com - 这需要适用于所有请求,因此 mydomain.com/whatever 会转到 sub.mydomain.com/whatever。
我已经尝试过了,它仅适用于主域中的非 www:
RewriteCond %{HTTP_HOST} ^mydomain.com [NC]
RewriteRule ^(.*)$ http://sub.mydomain.com/$1 [L,R=301]
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]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您也可以将它们压缩为一个规则:
Mark 关于
/
的观点是一个重要的考虑因素。由于您在.htaccess
中定义规则,因此输入(以及通过关联捕获的反向引用)不会以前导斜杠开头,因此在这种情况下您实际上确实需要一个显式斜杠(例如你有)。由于我们只想要整个路径,因此从这个意义上来说,使用
%{REQUEST_URI}
更可靠,因为它始终有一个前导斜杠,无论我们在什么上下文中使用该规则。You could condense them into a single rule as well:
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.另请注意:
还需要注意的一件事是,您可能不希望
RewriteRule
中的最后一个/
,因为它会向重定向的 URL 添加两个斜杠(例如 <代码>http://mydomain.com/foo.html 变为http://sub.mydomain.com//foo.html
)。Also add:
One thing also to note is you likely don't want that last
/
in yourRewriteRule
, as it'll add two slashes to the redirected URL (e.g.http://mydomain.com/foo.html
becomeshttp://sub.mydomain.com//foo.html
).