Apache:我如何才能使我的网站只能在SSL上使用,而不能通过HTTP和HTTPS?

我在Ubuntu服务器中有一个tomcat web应用程序。 Web应用程序被部署为ROOT 。 我已经安装了apache2并通过一个VirtualHost我指出的IP直接到tomcat的Web应用程序。 所以我可以直接通过IP(和域)访问网站,比如125.20.20.50example.com

请检查以下文件,该文件是\etc\apache2\sites-enabled\000-default.conf

 <VirtualHost *:80> ProxyPreserveHost On # Servers to proxy the connection, or; # List of application servers: # Usage: # ProxyPass / http://[IP Addr.]:[port]/ # ProxyPassReverse / http://[IP Addr.]:[port]/ # Example: ProxyPass / http://127.0.0.1:8080/ ProxyPassReverse / http://127.0.0.1:8080/ ServerName localhost </VirtualHost> <VirtualHost *:443> ServerAdmin webmaster@localhost DocumentRoot /opt/apache-tomcat-7.0.79/webapps/ROOT/ ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined SSLEngine On # Set the path to SSL certificate # Usage: SSLCertificateFile /path/to/cert.pem SSLCertificateKeyFile /etc/apache2/ssl/key.key SSLCertificateFile /etc/apache2/ssl/certificate.crt SSLCertificateChainFile /etc/apache2/ssl/STAR_xxx_com.ca-bundle ProxyPreserveHost On ProxyPass / http://localhost:8080/ ProxyPassReverse / http://localhost:8080/ ServerName localhost </VirtualHost> 

如果我专门在https://portal.example.com这样的URL中使用了https ,SSL工作正常。 这种情况是我仍然可以访问该网站没有安全性,如果我没有具体提到https但在浏览器中键入像portal.example.com

我怎样才能解决这个问题?

如果我正确地理解了您的意思,您希望http://portal.example.com/的所有访问被重写为https://portal.example.com

要做到这一点,你只需要用一个RewriteRulereplace端口80 VirtualHost中的ProxyPass的东西:

 <VirtualHost *:80>
    重写引擎
     RewriteRule ^(。*)$ https://portal.example.com/$1

     ServerName portal.example.com
 </虚拟主机>

这应该足以将所有内容重写为HTTPS页面。

注:这确实保留了url的其余部分,这意味着http://portal.example.com/random_page会变成https://portal.example.com/random_page

如果您只想将每个HTTP访问redirect到根HTTPS页面(因此http://portal.example.com/random_page将变为https://portal.example.com/ ),您应该接受@ HBruijn的答案,因为它对于这种情况要简单得多。

通常,您只需将用户从简单HTTP虚拟主机条目redirect到https:

 <VirtualHost *:80> ServerName portal.example.com Redirect / https://portal.example.com </VirtualHost> 

首先将您的VirtualHost更改为

 <VirtualHost *:80> ServerName portal.example.com DocumentRoot /opt/apache-tomcat-7.0.79/webapps/ROOT/ Redirect /secure https://portal.example.com </VirtualHost> 

PS:永远不要以root身份运行你的web服务器。 使用专用用户,并相应地在您的机器上授予其权利。