使用.htaccess强制SSL和WWW

时间:2014-07-12 08:20:00

标签: .htaccess ssl web https

我想知道.htaccess中用于强制URL中的SSL和WWW的代码是否正确,因为使用其他代码我通常会获得重定向循环,例如RewriteCond %{HTTPS} !=on现在它就像一个魅力(可疑)。还有,可以写得更好/更简单吗?

# Force to SSL
RewriteCond %{HTTP:HTTPS} !1
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

# Force to WWW
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]  

7 个答案:

答案 0 :(得分:40)

这有点简单。

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteRule ^(.*)$ https://www.domain.com/$1 [L,R=301]

答案 1 :(得分:33)

使用此:

RewriteEngine on

# Force www: from http://stackoverflow.com/a/4958847/1078583
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Force SSL: From http://stackoverflow.com/q/24322035/
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L,NE]

答案 2 :(得分:3)

很抱歉碰到这个话题,但我只是想为搜索引擎访问者添加一个简单的解决方案。

RewriteEngine on
# Force WWW & SSL
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.stackoverflow.com/$1 [L,R=301] 

答案 3 :(得分:1)

9 Force www:非常感谢你。

我的服务器是Heart Internet,而Heart for Heart是:

# All calls go to SSL
RewriteEngine On
RewriteCond %{ENV:HTTPS} !=on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

答案 4 :(得分:0)

我找到了一个mod_rewrite解决方案,该解决方案对于代理服务器和非代理服务器都适用。

如果您正在使用CloudFlare,AWS Elastic Load Balancing,Heroku,OpenShift或任何其他Cloud / PaaS解决方案,并且遇到使用常规HTTPS重定向的重定向循环,请尝试以下代码段。

$&

答案 5 :(得分:0)

无需填写域。无论如何,这都会强制 WWW HTTPS

RewriteEngine On

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

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

答案 6 :(得分:0)

我遇到了同样的问题,我用它来解决。效果最好。

RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L,NE]