温馨提示×

centos怎么配置apache证书

小樊
45
2026-08-03 22:39:46
栏目: 智能运维

CentOS 上配置 Apache HTTPS 证书,常见有 自签名证书Let’s Encrypt 免费证书 两种方式。下面按 最常用、最实用 的顺序说明。


一、准备工作

1. 安装 Apache(如已安装可跳过)

yum install -y httpd
systemctl enable httpd
systemctl start httpd

2. 开启 SSL 模块

yum install -y mod_ssl

安装完成后会自动生成:

/etc/httpd/conf.d/ssl.conf

二、方式一:使用 Let’s Encrypt(推荐 ✅)

1. 安装 Certbot

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

2. 申请证书(自动配置 Apache)

certbot --apache -d example.com -d www.example.com

按提示操作:

  • 输入邮箱
  • 同意协议
  • 是否转发 HTTP → HTTPS(建议选 2

3. 验证是否成功

浏览器访问:

https://example.com

4. 自动续期(重要)

certbot renew --dry-run

Certbot 已默认配置 cron / systemd 定时任务。


三、方式二:自签名证书(仅测试用)

1. 生成私钥和证书

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

2. 配置 Apache SSL

编辑:

vim /etc/httpd/conf.d/ssl.conf

修改关键配置:

SSLEngine on
SSLCertificateFile /etc/httpd/ssl/server.crt
SSLCertificateKeyFile /etc/httpd/ssl/server.key

确认监听端口:

Listen 443 https

3. 重启 Apache

systemctl restart httpd

浏览器会提示“不安全”,属于正常现象。


四、Apache 虚拟主机 HTTPS 示例(推荐写法)

<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>

五、HTTP 强制跳转 HTTPS(可选)

<VirtualHost *:80>
    ServerName example.com
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</VirtualHost>

六、常见问题排查

1. HTTPS 无法访问

firewall-cmd --permanent --add-service=https
firewall-cmd --reload

2. Apache 启动失败

httpd -t
journalctl -xe

3. SELinux 干扰

setenforce 0   # 临时关闭(测试用)

正式环境建议:

setsebool -P httpd_can_network_connect 1

七、总结建议

场景 推荐方式
生产环境 ✅ Let’s Encrypt
内网 / 测试 自签名
长期稳定 Certbot + 自动续期

如果你愿意,可以告诉我:

  • CentOS 版本(7 / 8 / Stream)
  • Apache 是否已安装
  • 域名是否已解析

我可以给你 完全针对你服务器的配置命令

0