我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?

我用的是PHP。


当前回答

 Redirect 301 / https://example.com/

(当上面的答案都没用的时候,对我来说是有效的)

奖金:

ServerAlias www.example.com example.com

(固定https://www.example.com未找到)

其他回答

如果希望从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步。

这将重定向所有的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]

把这段代码放到你的。htaccess文件中 自动将HTTP重定向到HTTPS

RewriteEngine上 重写%{HTTPS} off RewriteRule ^(. *)美元https://% {HTTP_HOST} % {REQUEST_URI} (L, R = 301)

 Redirect 301 / https://example.com/

(当上面的答案都没用的时候,对我来说是有效的)

奖金:

ServerAlias www.example.com example.com

(固定https://www.example.com未找到)

以上内容仅适用于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();
}