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

我用的是PHP。


当前回答

我喜欢这种从http重定向到https的方法。因为我不需要为每个网站编辑它。

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

其他回答

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

Apache文档不建议使用重写:

要重定向http url到https,请执行以下操作: < VirtualHost *: 80 > ServerName www.example.com 重定向/ https://www.example.com/ < /虚拟主机> < VirtualHost *: 443 > ServerName www.example.com #……SSL配置在这里 < /虚拟主机>

这段代码应该放在主服务器配置文件中,而不是像问题中要求的那样放在.htaccess中。

这篇文章可能是在问题被提出和回答之后才出现的,但似乎是目前的做法。

这将重定向所有的url到https和www

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTPS_HOST} !^www.example.com$ [NC,OR]
RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$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

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

如果你使用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']); 
}