我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?
我用的是PHP。
我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?
我用的是PHP。
当前回答
除非你需要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/(我正在做的一个网站)。
其他回答
经过多次尝试,考虑没有www和有www,这是可行的
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} (www\.)?yourdomain.com
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
以上内容仅适用于Apache服务器。如果在tomcat上运行PHP会怎样?
所以你可以使用PHP代码,无论是Apache/tomcat/Nginx等…
if (!((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))){
$redirect = 'https://' . str_replace($_SERVER['SERVER_PORT'], 8443, $_SERVER['HTTP_HOST']) . $_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $redirect);
exit();
}
Apache文档不建议使用重写:
要重定向http url到https,请执行以下操作: < VirtualHost *: 80 > ServerName www.example.com 重定向/ https://www.example.com/ < /虚拟主机> < VirtualHost *: 443 > ServerName www.example.com #……SSL配置在这里 < /虚拟主机>
这段代码应该放在主服务器配置文件中,而不是像问题中要求的那样放在.htaccess中。
这篇文章可能是在问题被提出和回答之后才出现的,但似乎是目前的做法。
这将会有帮助。
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?
除非你需要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/(我正在做的一个网站)。