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

我用的是PHP。


当前回答

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

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

其他回答

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

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

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


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

我发现最好的方式https和www域名是

RewriteCond %{HTTPS} off 
RewriteCond %{HTTPS_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

这是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

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