我试图重定向所有不安全的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]

其他回答

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

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

(当上面的答案都没用的时候,对我来说是有效的)

奖金:

ServerAlias www.example.com example.com

(固定https://www.example.com未找到)

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

除非你需要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/(我正在做的一个网站)。

按照上面解释的方法进行重定向。只需添加“HTTP严格传输安全”到您的头。这样可以避免中间的人攻击。

编辑apache配置文件(例如/etc/apache2/sites-enabled/website.conf和/etc/apache2/httpd.conf),并将以下内容添加到VirtualHost:

# Optionally load the headers module:
LoadModule headers_module modules/mod_headers.so

<VirtualHost 67.89.123.45:443>
    Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"
</VirtualHost>

https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security