301从主域(www和非www)重定向到子域

发布于 2024-09-14 22:50:47 字数 295 浏览 4 评论 0原文

我需要从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

何必那么矫情 2024-09-21 22:50:47

您也可以将它们压缩为一个规则:

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

Mark 关于 / 的观点是一个重要的考虑因素。由于您在 .htaccess 中定义规则,因此输入(以及通过关联捕获的反向引用)不会以前导斜杠开头,因此在这种情况下您实际上确实需要一个显式斜杠(例如你有)。

由于我们只想要整个路径,因此从这个意义上来说,使用 %{REQUEST_URI} 更可靠,因为它始终有一个前导斜杠,无论我们在什么上下文中使用该规则。

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.

七分※倦醒 2024-09-21 22:50:47

另请注意:

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

还需要注意的一件事是,您可能不希望 RewriteRule 中的最后一个 / ,因为它会向重定向的 URL 添加两个斜杠(例如 <代码>http://mydomain.com/foo.html 变为http://sub.mydomain.com//foo.html)。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文