我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?
我用的是PHP。
我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?
我用的是PHP。
当前回答
如果你正在使用Apache, mod_rewrite是最简单的解决方案,网上有很多关于如何做到这一点的文档。例如:http://www.askapache.com/htaccess/http-https-rewriterule-redirect.html
其他回答
最佳解决方案取决于您的需求。这是对之前发布的答案的总结,并添加了一些上下文。
如果你使用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']);
}
这是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
在.htaccess文件中使用以下代码自动将访问者重定向到站点的HTTPS版本:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
如果你有一个现有的。htaccess文件:
不要重复“重写引擎”。
确保以RewriteCond和RewriteRule开头的行立即跟随已经存在的RewriteEngine On。
这将重定向所有的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]
我发现最好的方式https和www域名是
RewriteCond %{HTTPS} off
RewriteCond %{HTTPS_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]