从 HTTP 强制使用 HTTPS(Apache)

从 HTTP 强制使用 HTTPS(Apache)

在 Apache 2 上将所有流量从 http 重新路由到 https 的最佳方法是什么?

所有对 80 的请求都应转到 443。

(我正在使用 Ubuntu + Apache 2)

答案1

扩展 freiheit 的答案,删除一些冗余部分,消除对 mod_rewrite 的依赖(以及相关的速度损失),并增加一些安全性:

<VirtualHost 1.2.3.4:80>
        ServerName SSL.EXAMPLE.COM
        CustomLog /var/log/httpd/EXAMPLE.access_log combined
        ErrorLog /var/log/httpd/EXAMPLE.error_log

        Redirect / https://ssl.example.com/
</VirtualHost>

<VirtualHost 1.2.3.4:443>
    ServerName ssl.example.com
    DocumentRoot /var/www/html
    CustomLog /var/log/httpd/EXAMPLE.ssl_access_log combined
    ErrorLog /var/log/httpd/EXAMPLE.ssl_error_log
    SSLEngine on
    SSLProtocol all -SSLv2
    SSLCipherSuite HIGH:MEDIUM
    .
    .
    .
</VirtualHost>

<Directory /var/www/html>
    #If all else fails, this will ensure nothing can get in without being encrypted.
    SSLRequireSSL
</Directory>

答案2

就我个人而言,我最喜欢的是简单地将所有端口 80 流量重定向到端口 443:

<VirtualHost 1.2.3.4:80>
        ServerName SSL.EXAMPLE.COM
        ServerAlias SSL
        DocumentRoot /var/www/html
        CustomLog /var/log/httpd/EXAMPLE.access_log combined
        ErrorLog /var/log/httpd/EXAMPLE.error_log

        RewriteEngine on
        RewriteRule .* https://SSL.EXAMPLE.COM/ [NC,R,L]
</VirtualHost>

<VirtualHost 1.2.3.4:443>
    ServerName ssl.example.com
    DocumentRoot /var/www/html
    CustomLog /var/log/httpd/EXAMPLE.ssl_access_log combined
    ErrorLog /var/log/httpd/EXAMPLE.ssl_error_log
    SSLEngine on
    SSLProtocol all -SSLv2
    SSLCipherSuite HIGH:MEDIUM
    .
    .
    .
</VirtualHost>

答案3

RewriteCond %{SERVER_PORT} ^80$
RewriteRule ^/(.*) https://你的服务器名称/$1[红]

相关内容