如何在htaccess中将多个域从非www重定向到www

时间:2014-01-30 10:42:48

标签: .htaccess http-status-code-301

我有5个独特的无关域名。在主域(托管包具有根文件夹与文件夹中的其他域)我需要将所有非www网址重定向到www。我在主域上的.htaccess文件中使用了这段代码:

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

它适用于主域名,但现在让我所有其他域名(例如www.myothersite.com)转到这样的网址:

//mysite.co.za/myotherdomain.com/home

我该如何防止这种情况。

2 个答案:

答案 0 :(得分:1)

简短且包含的 HTTPS

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

答案 1 :(得分:0)

正确的方法是:

# enable rewrite engine
RewriteEngine on
# if requested hostname does NOT start with "www."
RewriteCond %{HTTP_HOST} !^www\.
# get hostname to %1 variable
RewriteCond %{HTTP_HOST} ^([a-z]+\.[a-z]+)
# prepend "www." to requested hostname and file
RewriteRule (.*) http://www.%1/$1 [R=301,L]

如果您想更具体并且只包含某些域,请使用:

# enable rewrite engine
RewriteEngine on
# if requested hostname does NOT start with "www."
RewriteCond %{HTTP_HOST} !^www\.
# and if one of these hostnames, then get it to %1 variable
RewriteCond %{HTTP_HOST} ^(domain1\.com|domain2\.com|mysite\.co\.za)
# prepend "www." to requested hostname and file
RewriteRule (.*) http://www.%1/$1 [R=301,L]

因此,在RewriteCond %{HTTP_HOST} ^(domain1\.com|domain2\.com|mysite\.co\.za)行中,您将添加需要重定向的所有域。