在CentOS 7上配置Certbot以自动签发Nginx的HTTPS证书

鸿辰 Linux 707 0

概述

在Linux系统上自动签发免费的HTTPS证书,通常可以通过使用Let’s Encrypt证书颁发机构提供的自动化工具来实现。本文介绍使用 certbot 实现配置。

1. 安装Certbot

首先,您需要安装Certbot。由于CentOS 7默认的软件源可能不包含最新版本的Certbot,因此推荐使用Snap或直接从源代码安装。

1.1 安装Snapd

sudo yum install epel-release
sudo yum install snapd
sudo systemctl enable --now snapd.socket

1.2 通过Snap安装Certbot

sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot

如果这里报错 error: too early for operation, device not yet seeded or device model not acknowledged ,只需要执行下面的命令

sudo ln -s /var/lib/snapd/snap /snap

安装完成后再次执行命令通过Snap安装Certbot即可。

2. 配置Certbot自动签发证书

2.1 使用Certbot与Nginx集成来自动获取和配置HTTPS证书

sudo certbot --nginx -d test.com
  • 多个域名可以添加多个 -d your_domain,之间使用空格分隔,如 sudo certbot --nginx -d a.test.com -d b.test.com
  • 该工具检测默认的 nginx 配置目录在/etc/nginx,如果你的 nginx 不在该目录下,可以添加--nginx-server-root /path/to/your/nginx/conf 指定,如 nginx.conf 位于 /usr/local/nginx/conf/nginx.conf ,可以指定为 --nginx-server-root /usr/local/nginx/conf
  • 按照提示输入您的电子邮件地址,用于接收证书到期通知。
  • 同意Certbot的服务条款。输入输入大写的 Y

2.2 查看已颁发的证书

sudo certbot certificates

3. 续签证书

3.1 检查Certbot的续签配置

sudo certbot renew --dry-run

3.2 手动续签

sudo certbot --force-renewal

3.3 使用计划任务自动续签

如每天的凌晨2点运行,自动续签证书

# 平滑重启(建议)
sudo tee /etc/cron.d/certbot <<-'EOF'
0 2 * * * root certbot renew --quiet --post-hook "systemctl reload nginx"
EOF
# 强制重启
sudo tee /etc/cron.d/certbot <<-'EOF'
0 2  * *  *  root certbot renew --quiet --no-self-upgrade --renew-by-default --standalone --pre-hook "systemctl stop nginx" --post-hook "systemctl start nginx
EOF

4. 注意事项

因为certbot工具会自动修改你的域名对应的nginx配置,所以在签发完成后,请勿忘记检查nginx配置是否正确!

#推荐阅读

标签: https nginx