我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?
我用的是PHP。
我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?
我用的是PHP。
当前回答
按照上面解释的方法进行重定向。只需添加“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
其他回答
如果你正在使用Apache, mod_rewrite是最简单的解决方案,网上有很多关于如何做到这一点的文档。例如:http://www.askapache.com/htaccess/http-https-rewriterule-redirect.html
这是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
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 %{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>
在.htaccess文件中添加以下代码:
Options +SymLinksIfOwnerMatch
RewriteEngine On
RewriteCond %{SERVER_PORT} !=443
RewriteRule ^ https://[your domain name]%{REQUEST_URI} [R,L]
其中[您的域名]是您网站的域名。
你也可以重定向特定的文件夹从你的域名通过替换上面的最后一行代码:
RewriteRule ^ https://[your domain name]/[directory name]%{REQUEST_URI} [R,L]