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

我用的是PHP。


当前回答

更新:尽管这个答案在几年前就已经被接受了,但请注意,Apache文档现在不建议使用这种方法。改用重定向。请看这个答案。


RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

其他回答

Not only can you do this in your .htaccess file, you should be doing this period. You will also want to follow the steps here to get your site listed on the HSTS preload list after you implement this redirect so that any requests to the insecure http version of your website never make it past the user agent. Instead, the user agent checks the requested URI against a baked in list of https only websites and, if the requested URI is on that list, changes the protocol from http to https before transmitting the request to the server. Therefore, the insecure request never makes it out into the wild and never hits the server. Eventually when the internet changes over to https only the HSTS preload list will not be needed. Until then, every site should be using it.

为了执行重定向,我们需要启用重写引擎,然后将所有流量从http端口80重定向到https。

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://yourwebsite.tld/$1 [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>

如果希望从tomcat服务器执行以下步骤

在一个独立的Apache Tomcat (8.5.x) HTTP服务器中,如何配置它,以便如果用户输入www.domain.com,他们将被自动转发到https(www.domain.com)站点。

2步方法:在[Tomcat_base]/conf/web.xml的结束标记之前包含以下内容

step 1: 
<security-constraint>
<web-resource-collection>
<web-resource-name>HTTPSOnly</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>

设置[Tomcat_base]/conf/server.xml连接器设置:

step 2:
<Connector URIEncoding="utf-8" connectionTimeout="20000" port="80" protocol="HTTP/1.1" redirectPort="443"/>
<Connector port="443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true">
<SSLHostConfig>
<Certificate certificateKeystoreFile="[keystorelocation]" type="RSA" />
</SSLHostConfig>
</Connector>

注意:如果您已经进行了https配置并尝试重定向,则只执行第1步。

这将重定向所有的url到https和www

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

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