使用Certbot给域名加上ssl证书

2,620 阅读4分钟

CertBot是什么

说到CertBot就得先知道Let's Encrypt,Let's Encrypt是一个免费的数字证书颁发机构,通过自动化的方式为网站提供免费的SSL/TLS证书,以保护网站的数据安全。证书的有效期为90天,但可以通过自动续期来延长有效期。

Certbot是一个由Let's Encrypt官方提供的免费开源的工具,它可以帮助用户自动化地获得、续期和部署SSL/TLS证书。Certbot支持多种Web服务器,包括Apache、Nginx、Caddy等,用户可以使用Certbot来自动化地安装和配置SSL/TLS证书,以提高网站的安全性。

CertBot都有哪些命令行

  • certbot --help: 显示 Certbot 的帮助信息。
  • certbot certificates: 列出当前系统上安装的证书。
  • certbot renew: 尝试更新所有已安装的证书,如果证书即将过期则会自动重新签发。通常需要定期运行此命令以确保证书及时更新。
  • certbot revoke --cert-path /path/to/cert.pem: 吊销指定路径下的证书。
  • certbot delete --cert-name example.com: 删除指定名称的证书。
  • certbot certonly --webroot -w /path/to/webroot -d example.com -d www.example.com: 使用 webroot 插件验证并签发证书,其中 /path/to/webroot 是包含站点文件的根目录,example.comwww.example.com 是要签发证书的域名。

这些命令只是 Certbot 的一小部分功能,更多的命令和选项可以通过 certbot --help 命令进行查看。

CerBot怎么安装使用

yum install certbot

如果执行了 certbot certonly --webroot -w /path/to/webroot -d example.com 命令成功地获取了证书,那么接下来你需要将获取到的证书配置到 Web 服务器中,以启用 HTTPS 访问。具体的操作步骤如下:

  1. /etc/letsencrypt/live/example.com/ 目录下可以找到证书文件和密钥文件,可以使用 ls 命令查看:

    bashCopy code
    ls /etc/letsencrypt/live/example.com/
    cert.pem  chain.pem  fullchain.pem  privkey.pem  README
    
  2. 修改 Web 服务器配置文件,启用 HTTPS 访问。具体的操作步骤和配置方式与你使用的 Web 服务器有关,这里以 Nginx 为例:

    • 在 Nginx 的配置文件中添加 HTTPS 监听器,并指定证书和密钥的路径:

      bashCopy code
      server {
          listen 443 ssl;
          server_name example.com;
          ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
          ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
          ...
      }
      
    • 重启 Nginx 服务,以使配置生效:

      nginx -s reload
      
  3. 如果你使用的是防火墙,需要打开 HTTPS 监听器的端口 443:

    sudo ufw allow 443/tcp
    
  4. 完成上述操作后,你就可以通过 HTTPS 访问你的网站了。在浏览器中访问 example.com,如果出现绿色的锁标志,表示 HTTPS 已启用。如果有问题,可以查看 Nginx 的日志文件以获取详细的错误信息。

但是有些时候我们的一些服务并没有根目录,例如一些后端服务,这时候使用 --webroot 就走不通了。certbot 还有另外一种模式 --standalone , 这种模式不需要指定网站根目录,他会自动启用服务器的443/80端口,来验证域名的归属。我们有其他服务(例如nginx)占用了443/80端口,就必须先停止这些服务,在证书生成完毕后,再启用。

certbot certonly --standalone -d example.com -d www.example.com

证书生成完毕后,我们可以在 /etc/letsencrypt/live/ 目录下看到对应域名的文件夹,里面存放了指向证书的一些快捷方式。

续期

  1. 配置自动续期:

Certbot证书的有效期为90天,为了避免证书过期,你需要配置自动续期。Certbot已经为你自动创建了一个systemd timer,用于在证书快过期时自动续期。你可以使用以下命令来检查timer是否启用:

  • systemctl list-timers: 查看激活的timer
  • systemctl list-timers -all: 查看所有的timer
  • systemctl start certbot-renew.timer: 开启timer
  1. 检查 systemd timer 配置
~ ls /lib/systemd/system/ | grep certbot
certbot-renew.service
certbot-renew.timer
  1. 如果使用systemctl list-timers没有看到certbot的定时器,就ls查看检查一下或者使用systemctl list-timers -all看有没有,如果有就使用systemctl start certbot-renew.timer开启,没有就使用systemctl enable certbot-renew.timer然后在使用systemctl start certbot-renew.timer 至于网上说的什么corn表达式,似乎没有这个好用