nginx使用certbot自动更新https免费证书

个人博客的 HTTPS 证书一直使用的是免费的 Let's Encrypt 。证书获取和自动 renew 方案是参考 Jerry Qu 提供的 acme-tiny. 这个方案脚本短小精悍,是自己喜欢的风格。

但前几天发现网站的证书过期了,尝试手动运行更新脚本,发现已经无法运行。想来这个方案已经用了6年多了,索性这次迁移到使用官方的 certbot 方案。简单记录了一下迁移步骤:

https://certbot.eff.org/lets-encrypt/ubuntubionic-other

1. 安装 snapd

需要说明的是 snapd 在 Ubuntu 16.04 及以后版本都是预装的,可以跳过这个步骤。而我的服务器还停留在 14.04, 需要安装手动安装一遍:

apt-get install snapd

If you’re running Ubuntu 16.04 LTS (Xenial Xerus) or later, including Ubuntu 18.04 LTS (Bionic Beaver), Ubuntu 18.10 (Cosmic Cuttlefish) and Ubuntu 19.10 (Eoan Ermine), you don’t need to do anything. Snap is already installed and ready to go.

2. 安装 Certbot

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

3. 申请证书

因为服务器上部署了很多服务,有开源的nginx,也有自己编写的web服务,因此我仅使用 certbot 来获取和更新证书即可。证书的使用通过 post hooks 来集成。而我又不想停止我线上的服务,因此,这里使用 certonly 模式来获取证书

sudo certbot certonly –webroot -w /var/www/challenges -d www.liudanking.com -d liudanking.com

需要注意一点,需要映射一下 http 服务 /.well-known/acme-challenge path 与本地 directory 的关系。以nginx为例,可以这样配置:

To use the webroot plugin, your server must be configured to serve files from hidden directories. If /.well-known is treated specially by your webserver configuration, you might need to modify the configuration to ensure that files inside /.well-known/acme-challenge are served by the webserver.

一般,获取的证书会保存到 /etc/letsencrypt/live/DOMAIN_NAME 文件夹下,同时certbot后台也会运行一个定时调度任务,自动更新证书,防止证书过期。

4. 配置后处理钩子脚本

/etc/letsencrypt/renewal-hooks/post 添加后处理脚本renew_post.sh。这里我只需要见到的reload nginx即可:

nginx -s reload

这样,每次更新完证书,最新的证书就可以在nginx中应用生效了。

小结

certbot 整体流程还是比较简单的。但是绑定 snap 的方式不是自己喜欢的风格。考虑到这是 Let's Encrypt 官方推荐的方式,希望能够长期稳定吧。

之前在 Jerry Qu 的网站学习和参考了挺多 HTTPS 的知识和实践经验,挺感谢站长以及他的网站。今天回头看的时候,发现他已经有挺长时间没更新了,心有所触。不知道个人blog时代是不是已经远去不可及,也不知道自己还能坚持,权当是闲暇时候的反观世界时的喃喃自语吧。