使用Certbot申请免费的https证书

引子

此乃2025年第一篇文章,有一个好的开头。

之前服务器需要部署一个项目,node从12升到18,Ubuntu需要升级glibc(dddd),系统是ubuntu 16的难以更新,折腾了两天实在搞不定直接更换系统盘,使操作系统升级到24,一切从零开始。 于是乎年底了重新折腾了下博客,需要用到SSL证书,以前都是阿里云的免费证书一次一年,但突然发现有效期变成3个月了,这就很难受了,于是 Certbot 进入视野当中……

使用Certbot

Certbot 是一个免费的开源工具,用于自动配置 SSL/TLS 证书。它通过 Let’s Encrypt 提供证书服务。以下是 Certbot 的使用指南:

在 Ubuntu 上

sudo apt update
sudo apt install certbot python3-certbot-nginx  # 如果使用 Nginx

创建 Nginx 配置文件

server {
    listen 80;
    server_name www.yourdomain.com;

    # 如果有具体的项目目录,可以指向它
    root /path/to/your/project;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }
}

测试并重启 Nginx

sudo nginx -t
sudo systemctl reload nginx

运行 Certbot 命令

使用 Certbot 自动配置 HTTPS:

sudo certbot --nginx -d www.yourdomain.com

Certbot 会自动检测 Nginx 配置并尝试为你的域名申请证书。过程中会提示是否自动重写 HTTP 到 HTTPS,建议选择 “Yes”。

验证 HTTPS 配置

Certbot 成功运行后,Nginx 配置文件会被自动修改为 HTTPS。例如:

server {
    listen 443 ssl;
    server_name www.yourdomain.com

    ssl_certificate /etc/letsencrypt/live/www.yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.yourdomain.com/privkey.pem;

    root /path/to/your/project;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }
}

server {
    listen 80;
    server_name www.yourdomain.com;
    return 301 https://$host$request_uri;
}

自动续期

Certbot 自动生成的证书有效期为 90 天,建议配置自动续期:

sudo crontab -e

添加以下行以每天凌晨检查证书续期:

0 0 * * * certbot renew --quiet

手动检查和优化配置

重启 Nginx

Certbot 修改完配置后会自动重载 Nginx。如果需要手动操作:

sudo nginx -t  # 检查配置文件是否正确
sudo systemctl reload nginx  # 重载配置

启用 HTTP/2(可选)

listen 443 ssl 后添加 http2

listen 443 ssl http2;

自定义安全设置

Certbot 的配置已足够安全,但可以进一步优化,如:

禁用旧的 TLS 版本:

ssl_protocols TLSv1.2 TLSv1.3;

添加更严格的加密套件:

ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
Last Updated 2025/1/3 11:09:42