centos下nginx使用Let's Encrypt 申请免费 SSL 证书

发布时间 2023-06-19 15:42:49作者: 八戒vs

应用场景:想使用https,但是又不想花钱购买证书,也不是阿里和腾讯的可以免费申请

以下是具体操作步骤:

1.配置 DNS 记录
在申请二级域名 SSL 证书之前,需要先将该二级域名解析到您的服务器 IP 地址。

2.安装 Certbot:
Certbot 是 Let’s Encrypt 官方提供的工具,可用于自动化 SSL 证书的获取和安装。需要先确保您的服务器上已经安装了 Certbot 工具。

如果使用的是 CentOS 7 系统,可以按照以下步骤安装 Certbot 工具:
sudo yum install -y certbot-nginx

如果使用的是 CentOS 8 系统,可以使用以下命令安装 Certbot 工具:
sudo dnf install -y certbot-nginx

3.申请 SSL 证书:
在 Nginx 服务器上申请 SSL 证书时,需要执行以下命令:
sudo certbot --nginx -d sub.example.com

其中,sub.example.com 是需要申请 SSL 证书的二级域名。执行以上命令后,Certbot 将自动获取并配置 SSL 证书,同时更新 Nginx 的配置文件。

4.配置定期更新
Let's Encrypt 的 SSL 证书有效期为90天,因此需要编写一个脚本或使用 Certbot 工具来定期更新证书。以下是示例命令:
sudo certbot renew --dry-run

以上命令将测试证书续订功能是否正常工作。如果一切正常,可以使用以下命令设置自动更新:
sudo systemctl enable certbot.timer

5.如果报错sudo systemctl enable certbot.timer Failed to execute operation: No such file or directory

请检查 /etc/systemd/system/certbot.timer 文件是否存在,并确保其包含以下内容:

[Unit]
Description=Run the certbot renew twice a day

[Timer]
OnCalendar=*-*-* 00,12:00:00
RandomizedDelaySec=21600
Persistent=true

[Install]
WantedBy=timers.target

如果文件不存在,请使用以下命令创建该文件
touch /etc/systemd/system/certbot.timer

将上述文本粘贴到编辑器中,保存并关闭该文件。接下来,重新运行 sudo systemctl enable certbot.timer 命令,以启用 Certbot 定时器服务。