如何将非 www 重定向到我域中的 www

How to redirect non-www to www in my domain

我遇到问题我只想将 mydomain.com 重定向到 www.mydomain.com,但我找到的解决方案使我的 oder 子域像 admin.mydomain.com重定向到 www.admin.mydomain.com。 我有一个带有 Apache 的 Ubuntu 14.04 并使用 Laravel (PHP).

我只是希望在 mydomain.com/.... 到 www.mydomain.com/... 时发生这种情况,但是当开头有其他内容(例如 admin)时不会发生这种情况。mydomain.com

我把我找到的解决方案留在这里,但是我刚刚解释了这个小问题。

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/ [R=301,L]

这是我用来强制使用 www.

的规则
RewriteCond  %{HTTP_HOST} !^www\. [NC]
RewriteRule  ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

这应该只放在具有顶级域定义的 VirtualHost 内部

ServerName exmaple.com

每个其他子域都应该有自己的虚拟主机定义。

您可以指定要重定向的域:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/ [R=301,L]
# Redirect anything except admin.yourdomain.com, admin1.yourdomain.com
RewriteCond %{HTTP_HOST} !^(admin|admin1)\.yourdomain\.com$ [NC]
# Redirect to www.yourdomain.com, without changing the URI
RewriteRule ^(.*)$ http://www.yourdomain.com/ [L,R=302]

对于多个子域,这将有效

RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} ^yourdomain.com [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]