我试图重定向所有不安全的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步。
其他回答
如果你正在使用Apache, mod_rewrite是最简单的解决方案,网上有很多关于如何做到这一点的文档。例如:http://www.askapache.com/htaccess/http-https-rewriterule-redirect.html
我尝试了所有我能在互联网上找到的。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服务器
以上内容仅适用于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();
}
我发现了一种方法,强制我的网站的所有页面从http重定向到https的模拟页面,为我工作。
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
我发现最好的方式https和www域名是
RewriteCond %{HTTPS} off
RewriteCond %{HTTPS_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]