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

我用的是PHP。


当前回答

这对我来说很管用:

<IfModule mod_rewrite.c>
 RewriteEngine On
  RewriteCond %{HTTPS} !on
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

例如,http://server/foo?email=someone%40example.com可以正常重定向,没有任何问题。 文件.htaccess位于网站根文件夹(例如名为public_html)。 它是可以使用的 重写%{SERVER_PORT} !^443$ instead of重写%{HTTPS} !on

其他回答

这个问题的另一个优势是当负载均衡器开始发挥作用时。

情况如下: -从浏览器到负载均衡器的流量,以及返回,是(应该)HTTPS —负载均衡器与实际WebServer之间的流量为HTTP协议。

因此,PHP或Apache中的所有服务器请求变量都显示连接只是HTTP。服务器上的HTTP和HTTPS目录是相同的。

已批准答案中的重写条件不工作。 它要么是循环,要么就是不起作用。

问题是:如何让它在负载均衡器上工作。

(或者负载均衡器配置错误。这就是我所希望的,因为这样我就可以把问题转移到网络托管公司:-))

这是html重定向方法,它的工作,但不是最好的。

 <meta http-equiv="Refresh" content="0;URL=https://www.example.com" />

PHP方法

<?php
function redirectTohttps() {
    if ($_SERVER['HTTPS']!="on") {
        $redirect= "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        header("Location:$redirect"); 
    } 
}
?>

.htaccess approch

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

抄袭: www.letuslook.org

这对我来说很管用:

<IfModule mod_rewrite.c>
 RewriteEngine On
  RewriteCond %{HTTPS} !on
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

例如,http://server/foo?email=someone%40example.com可以正常重定向,没有任何问题。 文件.htaccess位于网站根文件夹(例如名为public_html)。 它是可以使用的 重写%{SERVER_PORT} !^443$ instead of重写%{HTTPS} !on

如果你正在使用亚马逊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流量。

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