我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?
我用的是PHP。
我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?
我用的是PHP。
当前回答
如果希望从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步。
其他回答
按照上面解释的方法进行重定向。只需添加“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
这个问题的另一个优势是当负载均衡器开始发挥作用时。
情况如下: -从浏览器到负载均衡器的流量,以及返回,是(应该)HTTPS —负载均衡器与实际WebServer之间的流量为HTTP协议。
因此,PHP或Apache中的所有服务器请求变量都显示连接只是HTTP。服务器上的HTTP和HTTPS目录是相同的。
已批准答案中的重写条件不工作。 它要么是循环,要么就是不起作用。
问题是:如何让它在负载均衡器上工作。
(或者负载均衡器配置错误。这就是我所希望的,因为这样我就可以把问题转移到网络托管公司:-))
我建议用301重定向:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
我尝试了所有我能在互联网上找到的。htaccess配置,但没有一个有效。 然后,我意识到Apache不鼓励使用mod_rewrite。
我的解决方案是在以下文件夹下编辑apache配置文件: /etc/apache2/sites-enabled
您将有一个名为000-default.conf的强制文件和一个名为000-default-le-ssl.conf的ssl配置文件(如果您从letsencrypt/certbot安装了ssl证书)。但是,这些文件的名称可能不同,这取决于您在设置网站时提供的文件名。
在000-default.conf中,我在<VirtualHost *:80>中编辑了以下内容:
<VirtualHost *:80>
ServerName example.com
Redirect / https://example.com/
</VirtualHost>
在000-default-le-ssl.conf中,我在<VirtualHost *:80>中编辑了以下内容:
<VirtualHost *:80>
ServerName example.com
Redirect / https://example.com/
</VirtualHost>
不需要其他重定向。
保存文件,然后使用sudo service apache2 restart重启apache服务器
我发现了一种方法,强制我的网站的所有页面从http重定向到https的模拟页面,为我工作。
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]