piczi
piczi
发布于 2025-08-02 / 10 阅读
0
0

终极指南:在 Ubuntu 上使用 Certbot 和阿里云 DNS 实现 HTTPS 证书全自动化

终极指南:在 Ubuntu 上使用 Certbot 和阿里云 DNS 实现 HTTPS 证书全自动化

本文是一份详尽的操作指南,旨在帮助您在 Ubuntu 系统上,利用 Certbot 和阿里云 DNS 插件,为您的域名(包括通配符域名)申请免费的 Let's Encrypt SSL 证书,并配置 Nginx 实现 HTTPS 访问,最终实现证书的自动续期和部署。本教程整合了从初始配置到常见问题排查的全过程,确保您能顺利完成部署。

第一步:准备工作

在开始之前,我们需要在阿里云和服务器上分别进行一些准备。

1.1 阿里云侧:创建 AccessKey

为了让 Certbot 能够通过 API 操作您的阿里云 DNS 记录,我们需要创建一个专用的 RAM 子用户并授予其 DNS 管理权限。

  1. 登录 阿里云 RAM 访问控制台 (https://ram.console.aliyun.com)。
  2. 在左侧导航栏选择 用户 -> 创建用户
  3. 填写登录名称和显示名称,并在“访问方式”中勾选 OpenAPI 调用访问
  4. 创建成功后,系统会生成一对 AccessKey IDAccessKey Secret请务必立即保存,这是后续操作的唯一凭证。
  5. 返回用户列表,为刚刚创建的用户 添加权限
  6. 在权限策略列表中,搜索并选择系统策略 AliyunDNSFullAccess,授权给该用户。

至此,阿里云侧的准备工作完成。

1.2 服务器侧:安装 Certbot 及插件

我们将使用 Ubuntu 官方仓库的 Certbot,并结合 Python 虚拟环境来安装阿里云 DNS 插件,以避免污染系统环境。

  1. 安装基础工具

    sudo apt update
    sudo apt install -y certbot python3-pip python3-venv
    
  2. 创建并激活 Python 虚拟环境
    官方推荐此方案,以保证插件环境的纯净。

    # 创建虚拟环境(目录可自定义,/opt/certbot 是一个不错的选择)
    sudo python3 -m venv /opt/certbot
    
    # 激活虚拟环境
    source /opt/certbot/bin/activate
    
  3. 在虚拟环境中安装插件
    激活环境后,我们来安装 Certbot 和阿里云 DNS 插件。

    # 升级 pip
    pip install --upgrade pip
    
    # 安装 certbot 和 aliyun 插件
    pip install certbot certbot-dns-aliyun
    

    权限问题排查:如果在执行 pip install 时遇到 Permission denied 错误,这是因为 /opt/certbot 目录由 sudo 创建。解决方法是在 root 权限下执行 pip 命令

    # 方法一:切换到 root 再操作
    sudo -s
    source /opt/certbot/bin/activate
    pip install --upgrade pip
    pip install certbot certbot-dns-aliyun
    deactivate
    exit
    
    # 方法二:直接使用 sudo 执行虚拟环境中的 pip
    sudo /opt/certbot/bin/pip install --upgrade pip
    sudo /opt/certbot/bin/pip install certbot certbot-dns-aliyun
    
  4. 验证插件安装
    确保 Certbot 已经能识别到阿里云插件。

    # 注意:必须使用虚拟环境内的 certbot 路径
    /opt/certbot/bin/certbot plugins | grep aliyun
    

    如果输出中包含 dns-aliyun,则说明安装成功。

第二步:申请证书

2.1 写入阿里云密钥

将第一步获取的 AccessKey 保存到服务器的一个安全文件中。

# 创建并写入密钥文件
sudo mkdir -p /etc/letsencrypt
sudo tee /etc/letsencrypt/aliyun.ini >/dev/null <<'EOF'
# 注意:键名必须是 dns_aliyun_access_key 和 dns_aliyun_access_key_secret
dns_aliyun_access_key = AKxxxxxxxxxxxxxxxx
dns_aliyun_access_key_secret = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
EOF

# 锁定文件权限,确保安全
sudo chmod 600 /etc/letsencrypt/aliyun.ini

2.2 首次申请通配符证书

现在,执行命令来申请证书。我们将同时申请主域名和通配符域名。

sudo /opt/certbot/bin/certbot certonly \
  --authenticator dns-aliyun \
  --dns-aliyun-credentials /etc/letsencrypt/aliyun.ini \
  -d "*.example.com" -d example.com \
  --email your@example.com --agree-tos --no-eff-email
  • example.comyour@example.com 替换为您自己的信息。
  • 插件会自动在阿里云 DNS 添加 TXT 记录进行验证,成功后会自动删除。

成功后,证书文件将保存在 /etc/letsencrypt/live/example.com/ 目录下。

申请过程问题排查

  • AliError: Specified access key is not found:此错误 99% 是因为 aliyun.ini 文件中的键名写错。请确保是 dns_aliyun_access_keydns_aliyun_access_key_secret,而不是其他变体。
  • Unable to determine zone identifier for ...:此错误意味着 Certbot 拿着你的 Key 去阿里云,却找不到你申请的域名。请检查:
    1. 登录阿里云控制台,确认该域名在当前 AccessKey 所属账号的云解析 DNS列表中。
    2. 确认该域名的 DNS 服务器已修改为阿里云的 ns1.alidns.comns2.alidns.com

第三步:配置 Nginx 使用证书

证书到手后,我们需要配置 Web 服务器(以 Nginx 为例)来启用 HTTPS。

3.1 通用 HTTPS 参数

为了方便管理和复用,建议创建一个通用的 SSL 参数配置文件。

新建 /etc/nginx/snippets/ssl-params.conf

# 安全的 TLS 协议和加密套件
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;

# 开启会话复用和 OCSP Stapling 提升性能和安全性
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;

# HSTS (HTTP Strict Transport Security)
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;

3.2 部署静态网站(示例:static.example.com

如果您的子域名仅用于托管静态文件(HTML, CSS, JS, 图片等),无需启动后端服务。

  1. 准备目录和文件

    sudo mkdir -p /var/www/static-site
    sudo chown -R www-data:www-data /var/www/static-site
    # 放入您的 index.html 等文件
    
  2. Nginx 配置
    新建 /etc/nginx/conf.d/static.example.com.conf

    server {
        listen 80;
        server_name static.example.com;
        return 301 https://$host$request_uri;
    }
    
    server {
        listen 443 ssl http2;
        server_name static.example.com;
    
        # 引用通配符证书
        ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
        include snippets/ssl-params.conf;
    
        # 指向静态文件根目录
        root /var/www/static-site;
        index index.html;
    
        # 对于单页应用 (SPA),使用 try_files 处理路由
        location / {
            try_files $uri $uri/ /index.html;
        }
    }
    

3.3 部署反向代理网站(示例:app.example.com

如果您的应用是一个后端服务(如 Node.js, Python, Java),Nginx 则作为反向代理。

新建 /etc/nginx/conf.d/app.example.com.conf

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

server {
    listen 443 ssl http2;
    server_name app.example.com;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    include snippets/ssl-params.conf;

    location / {
        # 代理到本地 3000 端口的后端服务
        proxy_pass http://127.0.0.1:3000;
        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;
    }
}

Nginx 配置问题排查

  • 403 Forbidden:通常是 Nginx 工作进程(默认为 www-data 用户)没有权限读取网站文件。如果您的项目放在 /home/your_user/ 目录下,www-data 无法访问。
    • 推荐方案:将网站文件移动到 /var/www/ 目录下,并执行 sudo chown -R www-data:www-data /var/www/your-project
    • 一劳永逸方案:编辑 /etc/nginx/nginx.conf,将 user www-data; 修改为 user your_user;,然后重启 Nginx。这样 Nginx 就以您的用户身份运行,可以访问您家目录下的所有文件。
  • 502 Bad Gateway:表示 Nginx 无法连接到 proxy_pass 指定的后端服务。请检查:
    1. 您的后端应用是否已启动?使用 ps aux | grep <端口号>ss -lntp | grep <端口号> 确认。
    2. 后端应用监听的端口是否与 Nginx 配置中的端口一致?

3.4 重载 Nginx

完成所有配置后,检查语法并平滑重载 Nginx。

sudo nginx -t && sudo systemctl reload nginx

第四步:实现自动续期

Let's Encrypt 证书有效期为 90 天,必须配置自动续期。

4.1 配置定时任务 (Crontab)

我们将使用 crontab 来定期执行续期命令。

  1. 打开 root 用户的定时任务编辑器:

    sudo crontab -e
    
  2. 在文件末尾添加以下行:

    # 每天凌晨 3:12 检查并续期证书,成功后自动重载 Nginx
    12 3 * * * /opt/certbot/bin/certbot renew --quiet --deploy-hook "systemctl reload nginx"
    
    • --quiet:只有在出错时才输出信息。
    • --deploy-hook:在证书成功续期后执行的命令,这里是重载 Nginx 以加载新证书。

保存并退出编辑器即可。该任务会在系统重启后依然生效。

4.2 测试自动续期

我们可以使用 --dry-run 参数来模拟续期过程,而不会真正生成新证书。

sudo /opt/certbot/bin/certbot renew --dry-run

如果最后输出 Congratulations, all simulated renewals succeeded.,则代表您的自动续期配置完全正确。

4.3 确认自动续期已配置

想检查是否已成功配置了自动续期任务,可以运行以下命令:

sudo crontab -l | grep 'certbot' && echo "✅ 已配置自动续期" || echo "❌ 未找到自动续期任务"

至此,您已经成功地在 Ubuntu 服务器上配置了一套全自动、安全可靠的 HTTPS 服务。无论是静态网站还是动态应用,都可以通过此流程轻松实现证书的申请、部署和无人值守续期。


评论