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

其他回答

我建议用301重定向:

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

这对我来说很管用:

<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

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

要将所有http请求重定向到https,您可以使用:

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]

如果mod-rewrite没有启用,并且你在apache 2.4上,你也可以在If指令中使用Redirect将http请求重定向到https。

Apache 2.4。

<if "%{HTTPS} !~ /on/">
Redirect / https://www.example.com/
</if>

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

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