Ubuntu服务器上为nginx设置免费的SSL/TLS 证书

10 阅读3分钟

(1)使用 Let’s Encrypt(免费证书)

 Let’s Encrypt 提供免费的 SSL 证书,你可以通过它自动获取和安装证书,避免手动操作。安装 certbot 来简化过程。 

 1. 安装 certbot(根据你的操作系统,使用适当的命令): 在 Ubuntu 上: sudo apt update sudo apt install certbot python3-certbot-nginx 

2. 获取证书并自动配置 nginx: 运行以下命令,它会自动为你的域名生成证书并配置 nginx: sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com 

 3. 验证证书: 在证书安装完成后,你可以访问 yourdomain.com 来确认 SSL 是否成功启用。

(2)要实现 Let’s Encrypt 证书的 自动续期,你只需要配置一个 Cron 任务(定时任务),让 certbot 每天自动检查并续期证书。certbot 会在证书接近到期时自动执行续期操作。

步骤:配置 certbot 自动续期

1. 检查 certbot 是否已安装

确保你已经安装了 certbot,并且它能够正常工作。如果还没有安装,可以参考以下命令安装:

sudo apt update
sudo apt install certbot python3-certbot-nginx

2. 测试手动续期

在设置自动续期之前,先测试一下手动续期是否有效:

sudo certbot renew --dry-run

--dry-run 选项是一个“试运行”选项,它模拟续期过程,而不会实际更改任何东西。如果这个命令输出没有错误,说明 certbot 的续期功能正常。

3. 自动续期配置

certbot 在安装时通常会自动设置好一个 cron 任务来处理证书的自动续期。如果没有设置或不确定是否已设置,可以手动添加一个 cron 任务。

使用 systemd 服务(推荐方式)

在 Ubuntu 系统中,certbot 通常会通过 systemd timer 来定期检查并续期证书,而不需要手动创建 cron 任务。你可以通过以下命令检查系统是否已经设置了自动续期:

sudo systemctl list-timers | grep certbot

如果输出了与 certbot 相关的 timer,表示它已经自动配置好。如果没有,接下来的步骤会帮助你手动设置。

4. 手动设置 Cron 任务(如果需要)

如果你没有看到 systemd timer,或者想使用 cron 来管理自动续期,按照以下步骤手动添加。

打开 crontab 配置文件:

sudo crontab -e

然后,添加以下行来每天运行 certbot 的续期命令:

0 0 * * * certbot renew --quiet

这条 cron 任务表示每天凌晨 0 点执行 certbot renew 命令。--quiet 参数表示如果没有错误发生,certbot 不会输出任何信息。

• 0 0 * * *:每天凌晨 0 点执行。

• certbot renew --quiet:尝试续期证书,如果已经有效则不做任何操作。

5. 验证 Cron 任务是否设置成功

保存并退出编辑器。你可以通过以下命令查看当前的 cron 任务,确认你的自动续期任务已添加:

sudo crontab -l

6. 测试自动续期是否有效

你可以模拟执行一次自动续期,确保它按预期工作:

sudo certbot renew --quiet

如果执行过程中没有错误,说明续期功能正常。

7. 重启 nginx 服务(可选)

在证书成功续期后,certbot 会自动重载 nginx,使新证书生效。但如果没有设置自动重载,你可以在 certbot renew 命令之后添加重启 nginx 的命令:

0 0 * * * certbot renew --quiet && systemctl reload nginx

这样确保每次证书续期后,nginx 会自动加载新的证书。

总结

• certbot 默认支持自动续期,你可以通过系统的 systemd timercron 任务 来定期执行续期操作。

• 一旦配置好,certbot 会每天检查证书是否需要续期,并自动进行续期。

• certbot renew --dry-run 可以模拟续期过程,确保续期配置正常。

• 在证书续期后,nginx 会自动加载新的证书,确保服务不间断。

如果你在某个步骤遇到问题或有其他疑问,随时告诉我!