htaccess为https域重写

时间:2015-10-21 10:03:51

标签: apache .htaccess mod-rewrite redirect https

我已将漏洞网店改为https。所以我想将除移动子域(http://m.my-store.com)之外的所有域重写为https://www.my-store.com

#First rewrite any request to the wrong domain to use the correct one (here www.)
#mobile subdomain shouldn't rewrite
RewriteCond %{HTTP_HOST} !m\.
RewriteCond %{HTTP_HOST} !^www\.my-store\.com$
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#Now, rewrite to HTTPS:
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^www\.my-store\.com$
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

结果:

http://my-store.com         OK (correct rewrite to https://www.my-store.com)
http://www.my-store.com     OK (correct rewrite to https://www.my-store.com)
https://my-store.com        X (stays with https://my-store.com)
https://www.my-store.com    OK (correct rewrite to https://www.my-store.com)
http://m.my-store.com       OK (correct rewrite to https://www.my-store.com)

1 个答案:

答案 0 :(得分:1)

如果www不在请求中,我会做的只是检查域而不是尝试匹配。而是反过来,只检查基本域,这意味着没有www,所以重定向。 您还可以利用[OR]和这一条规则来处理所有情况。

您遵守以下规则。

RewriteCond %{HTTP_HOST} ^my-store\.com$ [OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^m\.
RewriteRule ^(.*)$ https://www.my-store.com/$1 [L,R=301]

请不要在下面这样做。

我在上面的重写中使用了实际的域,因此您不会遇到变量问题,因为您将使用此方法OR。这意味着你有这样的规则。

RewriteCond %{HTTP_HOST} ^my-store\.com$ [OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^m\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

您的请求http://www.my-store.com最终会得到https://www.www.my-store.com所以请使用我提供的第一条规则。

您的结果将使用上面的第一条规则。

http://my-store.com         (rewrites to https://www.my-store.com)
http://www.my-store.com     (rewrites to https://www.my-store.com)
https://my-store.com        (rewrites to https://www.my-store.com)
https://www.my-store.com    (does nothing - https://www.my-store.com)
http://m.my-store.com       (does nothing - http://m.my-store.com)
相关问题