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

我用的是PHP。


当前回答

在.htaccess文件中使用以下代码自动将访问者重定向到站点的HTTPS版本:

RewriteEngine On

RewriteCond %{HTTPS} off

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

如果你有一个现有的。htaccess文件:

不要重复“重写引擎”。

确保以RewriteCond和RewriteRule开头的行立即跟随已经存在的RewriteEngine On。

其他回答

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

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

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

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

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

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

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

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

最佳解决方案取决于您的需求。这是对之前发布的答案的总结,并添加了一些上下文。

如果你使用Apache web服务器并且可以更改其配置,请参考Apache文档:

<VirtualHost *:80>
    ServerName www.example.com
    Redirect "/" "https://www.example.com/"
</VirtualHost>

<VirtualHost *:443>
    ServerName www.example.com
    # ... SSL configuration goes here
</VirtualHost>

但你还问是否可以在.htaccess文件中进行。在这种情况下,你可以使用Apache的RewriteEngine:

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

如果一切正常,你想让浏览器记住这个重定向,你可以将最后一行更改为:

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

但如果你在这个方向上改变了主意,要小心。浏览器会记住它很长一段时间,不会检查它是否改变了。

根据web服务器配置,您可能不需要第一行RewriteEngine On。

如果你在寻找一个PHP解决方案,看看$_SERVER数组和header函数:

if (!$_SERVER['HTTPS']) {
    header("Location: https://" . $_SERVER['HTTP_HOST'] . $_SERVER['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]

这对我来说很管用:

<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