为Apache2配置SSL证书并使用重写模块强制https访问

配置SSL证书

证书签发机构会根据你所选的服务端类型响应对应的SSL证书文件, 对于Apache2, 证书文件如下

root_bundle.crt 证书文件
example.com.crt 证书文件
example.com.key 私钥文件
example.com.csr CSR文件

其中前三个是需要配置的文件, CSR文件无需关注.

将前三个文件放入/etc/apache2/ssl/文件夹中, 若无此文件夹, 可自行创建.

配置Apache2

首先开启SSL功能

a2enmod ssl

随后修改配置文件/etc/apache2/sites-available/default-ssl.conf为如下内容

<VirtualHost 0.0.0.0:443>
    DocumentRoot "/var/www/html" 
    #填写证书名称
    ServerName example.com
    #启用 SSL 功能
    SSLEngine on 
    #证书文件的路径
    SSLCertificateFile /etc/apache2/ssl/example.com.crt
    #私钥文件的路径
    SSLCertificateKeyFile /etc/apache2/ssl/example.com.key
    #证书链文件的路径
    SSLCertificateChainFile /etc/apache2/ssl/root_bundle.crt
</VirtualHost>

再为配置文件建立软链接使之生效

a2ensite default-ssl

随后在配置文件/etc/apache2/ports.conf中添加以下字段

<IfModule ssl_module>
    Listen 443
</IfModule>

使之监听https的443端口.

在使配置文件生效前检测配置文件语法是否正确

apache2ctl configtest

若输出

Syntax OK

则执行

systemctl reload apache2

重载配置文件.

此时可以访问https://example.com, 会发现链接安全, https已启用, 但此时若直接访问域名, 仍然走的是http协议, 接下来解决这个问题.

使用Apache2的重写模块强制https访问

在配置文件/etc/apache2/sites-available/000-default.conf中的<VirtualHost *:80>域内添加如下字段

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

然后开启重写模块

a2enmod rewrite

然后验证一下配置文件有无语法错误, 若验证通过重载配置文件

systemctl reload apache2

至此配置完成, 在浏览器直接输入域名则自动重定向至https协议.

posted @ 2022-03-27 21:04  方清欢  阅读(237)  评论(0编辑  收藏  举报