我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?
我用的是PHP。
我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?
我用的是PHP。
当前回答
根据GoDaddy.com,这是使用.htaccess将HTTP重定向到HTTPS的正确方法。第一行代码是自解释的。第二行代码检查HTTPS是否关闭,如果关闭,则通过运行第三行代码将HTTP重定向到HTTPS,否则将忽略第三行代码。
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
https://www.godaddy.com/help/redirect-http-to-https-automatically-8828
其他回答
在.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]
要将所有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>
这是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
如果希望从tomcat服务器执行以下步骤
在一个独立的Apache Tomcat (8.5.x) HTTP服务器中,如何配置它,以便如果用户输入www.domain.com,他们将被自动转发到https(www.domain.com)站点。
2步方法:在[Tomcat_base]/conf/web.xml的结束标记之前包含以下内容
step 1:
<security-constraint>
<web-resource-collection>
<web-resource-name>HTTPSOnly</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
设置[Tomcat_base]/conf/server.xml连接器设置:
step 2:
<Connector URIEncoding="utf-8" connectionTimeout="20000" port="80" protocol="HTTP/1.1" redirectPort="443"/>
<Connector port="443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true">
<SSLHostConfig>
<Certificate certificateKeystoreFile="[keystorelocation]" type="RSA" />
</SSLHostConfig>
</Connector>
注意:如果您已经进行了https配置并尝试重定向,则只执行第1步。
Apache文档不建议使用重写:
要重定向http url到https,请执行以下操作: < VirtualHost *: 80 > ServerName www.example.com 重定向/ https://www.example.com/ < /虚拟主机> < VirtualHost *: 443 > ServerName www.example.com #……SSL配置在这里 < /虚拟主机>
这段代码应该放在主服务器配置文件中,而不是像问题中要求的那样放在.htaccess中。
这篇文章可能是在问题被提出和回答之后才出现的,但似乎是目前的做法。