我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?

我用的是PHP。


当前回答

根据GoDaddy.com,这是使用.htaccess将HTTP重定向到HTTPS的正确方法。第一行代码是自解释的。第二行代码检查HTTPS是否关闭,如果关闭,则通过运行第三行代码将HTTP重定向到HTTPS,否则将忽略第三行代码。

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

https://www.godaddy.com/help/redirect-http-to-https-automatically-8828

其他回答

经过多次尝试,考虑没有www和有www,这是可行的

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} (www\.)?yourdomain.com
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

要将所有http请求重定向到https,您可以使用:

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]

如果mod-rewrite没有启用,并且你在apache 2.4上,你也可以在If指令中使用Redirect将http请求重定向到https。

Apache 2.4。

<if "%{HTTPS} !~ /on/">
Redirect / https://www.example.com/
</if>

正如我在这个问题中所说的,我建议您避免盲目地将所有HTTP请求重定向到其HTTPS对等物,因为这可能会使您对安全性产生错误的印象。相反,您应该将HTTP站点的“根”重定向到HTTPS站点的根,并从那里链接到HTTPS。

问题是,如果HTTPS站点上的某些链接或表单使客户端向HTTP站点发送请求,那么在重定向之前,其内容将是可见的。

例如,如果一个通过HTTPS提供服务的页面有一个<form action="http://example.com/doSomething">的表单,并且发送了一些不应该明确发送的数据,浏览器将首先将完整的请求(包括实体,如果它是POST)首先发送到HTTP站点。重定向将立即发送到浏览器,由于大量用户禁用或忽略警告,它很可能被忽略。

Of course, the mistake of providing the links that should be to the HTTPS site but that end up being for the HTTP site may cause problems as soon as you get something listening on the HTTP port on the same IP address as your HTTPS site. However, I think keeping the two sites as a "mirror" only increases the chances of making mistakes, as you may tend to make the assumption that it will auto-correct itself by redirecting the user to HTTPS, whereas it's often too late. (There were similar discussions in this question.)

如果你正在使用Apache, mod_rewrite是最简单的解决方案,网上有很多关于如何做到这一点的文档。例如:http://www.askapache.com/htaccess/http-https-rewriterule-redirect.html

Apache文档不建议使用重写:

要重定向http url到https,请执行以下操作: < VirtualHost *: 80 > ServerName www.example.com 重定向/ https://www.example.com/ < /虚拟主机> < VirtualHost *: 443 > ServerName www.example.com #……SSL配置在这里 < /虚拟主机>

这段代码应该放在主服务器配置文件中,而不是像问题中要求的那样放在.htaccess中。

这篇文章可能是在问题被提出和回答之后才出现的,但似乎是目前的做法。