配置 CertBot 域名证书

本文适用于 Ubuntu 操作系统,使用 Nginx 作为 Web 服务器。

安装 CertBot

sudo snap install certbot

申请域名证书

你可以先配置一个 80 端口的网站,Nginx 的配置模版如下

server {
    server_name some.domain.com;
    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
    listen 80;
}

完成好 Nginx 的配置后,使用 sudo nginx -s reload 来确认该配置已经生效,然后执行下方的命令。它将会在域名的证书申请成功后自动修订你的 Nginx 配置,加入 http -> https 自动跳转以及相关的证书配置。

sudo certbot --nginx -d some.domain.com

配置证书自动更新

申请好的证书有效的时间是 90 天,我们需要配置自动更新以防止 90 天后因证书过期而导致网站无法被正常访问。

建立 /etc/systemd/system/certbot-renew.service 文件

[Unit]
Description=Renew Let's Encrypt certificates (certbot snap)
Wants=network-online.target
After=network-online.target

[Service]
Type=oneshot
ExecStart=/usr/bin/snap run certbot renew --non-interactive --quiet --deploy-hook "systemctl reload nginx"

建立 /etc/systemd/system/certbot-renew.timer 文件

[Unit]
Description=Run certbot renew twice daily

[Timer]
OnCalendar=*-*-* 03,15:00:00
RandomizedDelaySec=30m
Persistent=true

[Install]
WantedBy=timers.target

将配置生效,执行以下的命令来确定

sudo systemctl daemon-reload
sudo systemctl enable --now certbot-renew.timer
systemctl list-timers --all | grep -i certbot

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注