删除" WWW"来自" {HTTP_HOST}"在htaccess规则中

时间:2016-05-02 08:43:43

标签: php apache .htaccess redirect ssl

我有3个网址并且有ssl认证

1)www.example.com

2)myexample.com

3)otherexample.com

我需要将以上三个网址重定向到https安全网址 例如:当用户打开上面任何一个url时,它应该重定向到https url。

=> when user open www.example.com OR example.com >>> it should redirect to https://www.example.com
=> when user open www.myexample.com OR myexample.com OR https://www.myexample.com >>> it should redirect to https://myexample.com
=> when user open www.otherexample.com OR otherexample.com OR https://www.otherexample.com >>> it should redirect to https://otherexample.com

注意:我有www.example.com的ssl证书,myexample.com(非www),otherexample.com(非www)

我需要帮助来解决我的问题。我也想动态设置规则,以便将来如果我有更多网址,那么就不会编辑.htaccess文件。 (如果可以从下面的{HTTP_HOST}设置规则中删除" www"那么这对我有好处)

我已经在htaccess中设定了规则,但它对我没有用。

RewriteCond %{HTTP_HOST} !^www\. [OR]
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}$1 [R=301,L]

#rule for myexample.com
RewriteEngine On
RewriteCond %{HTTP_HOST}  ^www.example.com [nocase]
RewriteRule ^(.*)         https://example.com/$1 [last,redirect=301]

#rule for otherexample.com
RewriteEngine On
RewriteCond %{HTTP_HOST}  ^www.otherexample.com [nocase]
RewriteRule ^(.*)         https://otherexample.com/$1 [last,redirect=301]

2 个答案:

答案 0 :(得分:0)

我希望它对你有用。

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

答案 1 :(得分:0)

尝试以下方法:

RewriteEngine on

#redirect any other domain that is not "www.example.com" to "https://"
RewriteCond %{HTTPS} off 
RewriteCond %{HTTP_HOST} (?:www\.)?((?!example\.com).+)$
RewriteRule ^ https://%1%{REQUEST_URI} [NE,L,R]
#redirect  "www.example.com" to "https://www"
RewriteCond %{HTTPS} off 
RewriteCond %{HTTP_HOST} (?:www\.)?((example\.com).+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]