CentOS配置SSL证书

在 CentOS 上配置 SSL 证书(以 Apache 为例)主要分为以下步骤:


一、准备工作

  1. 获取 SSL 证书文件(通常从证书颁发机构 CA 获取):

    • 证书文件(如 your_domain.crt
    • 私钥文件(如 your_domain.key
    • 证书链文件(如 ca_bundle.crt,可选但推荐)
  2. 安装 Apache 和 mod_ssl

    1
    sudo yum install httpd mod_ssl

二、配置 SSL 证书

1. 上传证书文件到服务器

将证书文件放到安全目录(如 /etc/pki/tls/certs/):

1
2
3
sudo cp your_domain.crt /etc/pki/tls/certs/
sudo cp your_domain.key /etc/pki/tls/private/ # 私钥放更安全的位置
sudo cp ca_bundle.crt /etc/pki/tls/certs/ # 证书链文件

2. 合并证书链(如果需要)

如果是单独证书+链文件,合并成一个文件:

1
sudo cat /etc/pki/tls/certs/your_domain.crt /etc/pki/tls/certs/ca_bundle.crt > /etc/pki/tls/certs/your_domain_combined.crt

3. 修改 Apache SSL 配置

编辑配置文件:

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

找到并修改以下参数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<VirtualHost *:443>
ServerName your_domain.com
DocumentRoot /var/www/html

# SSL 配置
SSLEngine on
SSLCertificateFile /etc/pki/tls/certs/your_domain_combined.crt # 证书文件(或合并后的文件)
SSLCertificateKeyFile /etc/pki/tls/private/your_domain.key # 私钥文件

# 可选:强制 HTTPS 重定向
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>
</VirtualHost>

4. 检查配置并重启 Apache

1
2
sudo apachectl configtest  # 检查语法错误
sudo systemctl restart httpd

三、防火墙放行 HTTPS

1
2
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

四、验证 SSL 配置

  1. 浏览器访问
    https://your_domain.com,检查地址栏是否有锁标志。

  2. 命令行验证

    1
    openssl s_client -connect your_domain.com:443 -servername your_domain.com

五、自签名证书(测试用)

生成自签名证书:

1
2
3
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout /etc/pki/tls/private/selfsigned.key \
-out /etc/pki/tls/certs/selfsigned.crt

配置 Apache:

修改 ssl.conf 指向自签名证书:

1
2
SSLCertificateFile /etc/pki/tls/certs/selfsigned.crt
SSLCertificateKeyFile /etc/pki/tls/private/selfsigned.key

常见问题排查

  1. 权限问题
    确保私钥仅 root 可读:

    1
    sudo chmod 600 /etc/pki/tls/private/your_domain.key
  2. SELinux 阻止访问
    检查日志 /var/log/audit/audit.log,或临时禁用 SELinux 测试:

    1
    sudo setenforce 0  # 临时关闭
  3. 端口冲突
    确保无其他进程占用 443 端口:

    1
    sudo netstat -tuln | grep 443

总结流程

1
2
3
4
5
6
7
graph TD
A[获取证书文件] --> B[上传到服务器]
B --> C[合并证书链]
C --> D[修改 ssl.conf]
D --> E[重启 Apache]
E --> F[配置防火墙]
F --> G[验证访问]

通过以上步骤,即可在 CentOS 上完成 SSL 证书配置。对于 Nginx 或其他服务,流程类似,主要差异在于配置文件路径和语法。