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

我用的是PHP。


当前回答

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]

其他回答

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

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


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

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

RewriteEngine On

RewriteCond %{HTTPS} off

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

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

不要重复“重写引擎”。

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

根据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