在 CentOS 上配置 Apache HTTPS 证书,常见有 自签名证书 和 Let’s Encrypt 免费证书 两种方式。下面按 最常用、最实用 的顺序说明。
yum install -y httpd
systemctl enable httpd
systemctl start httpd
yum install -y mod_ssl
安装完成后会自动生成:
/etc/httpd/conf.d/ssl.conf
CentOS 7
yum install -y epel-release
yum install -y certbot python2-certbot-apache
CentOS 8 / Stream
dnf install -y epel-release
dnf install -y certbot python3-certbot-apache
certbot --apache -d example.com -d www.example.com
按提示操作:
2)浏览器访问:
https://example.com
certbot renew --dry-run
Certbot 已默认配置 cron / systemd 定时任务。
mkdir -p /etc/httpd/ssl
cd /etc/httpd/ssl
openssl req -new -newkey rsa:2048 -nodes \
-keyout server.key \
-out server.csr
生成自签证书:
openssl x509 -req -days 365 \
-in server.csr \
-signkey server.key \
-out server.crt
编辑:
vim /etc/httpd/conf.d/ssl.conf
修改关键配置:
SSLEngine on
SSLCertificateFile /etc/httpd/ssl/server.crt
SSLCertificateKeyFile /etc/httpd/ssl/server.key
确认监听端口:
Listen 443 https
systemctl restart httpd
浏览器会提示“不安全”,属于正常现象。
<VirtualHost *:443>
ServerName example.com
DocumentRoot /var/www/html
SSLEngine on
SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
<Directory /var/www/html>
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
<VirtualHost *:80>
ServerName example.com
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</VirtualHost>
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
httpd -t
journalctl -xe
setenforce 0 # 临时关闭(测试用)
正式环境建议:
setsebool -P httpd_can_network_connect 1
| 场景 | 推荐方式 |
|---|---|
| 生产环境 | ✅ Let’s Encrypt |
| 内网 / 测试 | 自签名 |
| 长期稳定 | Certbot + 自动续期 |
如果你愿意,可以告诉我:
我可以给你 完全针对你服务器的配置命令。