如何使用 .htaccess 将 sub.example.com 重定向到 www.example.com?

How to redirect sub.example.com to www.example.com with .htaccess?

我想将 sub.example.com 重定向到 www.example.com。我使用了.htaccess 的重写。我写了这个:

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

我已经激活重写:sudo a2enmod rewrite。

而且我已经将 example.com 重写为 www.example.com :

RewriteCond %{HTTP_HOST} ^example.+$ [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

你知道在这种情况下我必须如何编写我的重写规则吗?

如果您指定域名,则两种情况都可以使用一个规则:

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