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

我用的是PHP。


当前回答

除非你需要mod_rewrite做其他事情,使用Apache核心IF指令更干净更快:

<If "%{HTTPS} == 'off'">
Redirect permanent / https://yoursite.com/
</If>

你可以在IF指令中添加更多的条件,比如确保一个没有www前缀的规范域:

<If "req('Host') != 'myonetruesite.com' || %{HTTPS} == 'off'">
Redirect permanent / https://myonetruesite.com/
</If>

使用mod_rewrite做任何事情都有很多熟悉的惯性,但看看这是否适合你。

更多信息:https://httpd.apache.org/docs/2.4/mod/core.html#if

要看到它的行动(尝试没有www。或https://,或用。net代替。com): https://nohodental.com/(我正在做的一个网站)。

其他回答

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

如果你正在使用亚马逊Web服务弹性负载均衡器,它接受https流量并通过http将其路由到你的服务器,这里描述了将所有http流量重定向到https的正确方法:https://aws.amazon.com/premiumsupport/knowledge-center/redirect-http-https-elb

使用X-Forwarded-Proto报头(包含http或https),它总是包含在来自负载均衡器的http请求中,如下所述:https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html

在httpd.conf文件中:

<VirtualHost *:80>

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]

</VirtualHost>

或者在你的根文件。htaccess中:

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]

好处:它不会尝试重定向本地开发机器上的http流量。

把这段代码放到你的。htaccess文件中 自动将HTTP重定向到HTTPS

RewriteEngine上 重写%{HTTPS} off RewriteRule ^(. *)美元https://% {HTTP_HOST} % {REQUEST_URI} (L, R = 301)

如果希望从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步。

我发现了一种方法,强制我的网站的所有页面从http重定向到https的模拟页面,为我工作。

RewriteEngine On 
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]