启用 mod_ssl 模块是开启 https 的前提,需手动加载、配置证书、监听 443 端口,并为每个站点单独定义 虚拟主机。

启用 Apache 的 mod_ssl 模块是开启 HTTPS 的前提,不是装了 Apache 就自动支持加密——它必须手动加载、配置证书、监听 443 端口,并为每个 HTTPS 站点单独定义虚拟主机。
确认并启用 mod_ssl 模块
Apache 默认不带 SSL 功能,mod_ssl 是独立模块,需显式安装和启用:
- Ubuntu/Debian:
sudo a2enmod ssl && sudo systemctl restart apache2 - CentOS/RHEL(含 Rocky/AlmaLinux):
sudo yum install -y mod_ssl openssl或dnf install -y mod_ssl openssl,安装后服务通常自动重启 - 验证是否成功:
apachectl -M | grep ssl(Ubuntu/Debian)或httpd -M | grep ssl(CentOS/RHEL),输出含ssl_module (shared)才算到位
确保 443 端口监听已启用
HTTPS 必须走 443 端口,仅启用模块还不够:
- 检查配置中是否存在
Listen 443(常见于/etc/apache2/ports.conf或/etc/httpd/conf.d/ssl.conf) - 若缺失,手动添加该行并保存;防火墙也要放行:
sudo ufw allow 443(Ubuntu)或sudo firewall-cmd --permanent --add-port=443/tcp(CentOS) -
SSLEngine on只在<virtualhost></virtualhost>块内生效,在*:80块里写完全无效
配置 HTTPS 虚拟主机与证书路径
每个需要 HTTPS 的站点,都得配一个专属的 <virtualhost></virtualhost> 块:
- 证书文件必须成对存在:
SSLCertificateFile(域名证书或合并后的 fullchain.pem)和SSLCertificateKeyFile(私钥) - 推荐路径规范:
/etc/ssl/certs/存证书,/etc/ssl/private/存私钥;私钥权限必须设为600:sudo chmod 600 /etc/ssl/private/example.com.key - 示例配置片段(替换域名和路径):
<virtualhost> ServerName example.com DocumentRoot /var/www/example SSLEngine on SSLCertificateFile /etc/ssl/certs/example.com.crt SSLCertificateKeyFile /etc/ssl/private/example.com.key </virtualhost>
可选:强制 HTTP 自动跳转 HTTPS
让访问者始终走加密链路,建议在 <virtualhost></virtualhost> 中加跳转规则:
- 用
Redirect最简洁:Redirect permanent / https://example.com/ - 或用重写规则(需
mod_rewrite):RewriteEngine on RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] - 配置完务必执行
sudo apachectl configtest(Ubuntu)或sudo httpd -t(CentOS)检查语法,再重启服务











