我试图重定向所有不安全的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
其他回答
按照上面解释的方法进行重定向。只需添加“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
Redirect 301 / https://example.com/
(当上面的答案都没用的时候,对我来说是有效的)
奖金:
ServerAlias www.example.com example.com
(固定https://www.example.com未找到)
我实际上试图让它在没有负载均衡器的EC2实例上工作,因为这需要花钱。我到处都读到。htaccess不是“正确”的方式。很明显,这是可行的,但我只是想按规矩办事。我按照所有示例更新httpd.conf文件,并添加了许多不必要的东西。事实证明,你真正需要的唯一一行是:
Redirect permanent / https://www.yourdomain.com
我的问题是,最初我已经在httpd.conf中的VirtualHost标签中添加了这个,这是很多帖子告诉你要做的,但它不起作用。原来有一个单独的conf文件存储在/etc/httpd/conf中。d调用yourdomain.conf,它已经有了VirtualHost标签,并且覆盖了我的httpd.conf设置。我只是添加了上面的行里面,瞧,它立即重定向到https。端口443不需要单独的VirtualHost。
它现在正在工作,VirtualHost标签看起来是这样的:
<VirtualHost *:80>
ServerName yourdomain.com
DocumentRoot /var/www/html
ServerAlias www.yourdomain.com
ErrorLog /var/www/error.log
CustomLog /var/www/requests.log combined
Redirect permanent / https://www.yourdomain.com
</VirtualHost>
注意:我已经从certbot(爱那些家伙)的免费证书设置了TLS,只是试图将常规http调用重定向到工作的https站点。
这是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
这将会有帮助。
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
此外,参考这更多的细节。如何重定向Http到Https?