← 返回

申请 HTTPS 证书

用 certbot 的 nginx 插件自动改配置、配续期定时器、把 http 跳去 https。域名要先解析到本机。

需要 root

一键执行

curl -fsSL https://www.moiu.cn/scripts/certbot-ssl.sh | bash

脚本源码

#!/usr/bin/env bash
# 申请 Let's Encrypt 证书
#
# 用 --nginx 插件:自动改配置、自动配好续期定时器、自动做 http → https 跳转。
# 前提:域名已经解析到本机,且 80 端口能从公网访问。
# 用法:bash certbot-ssl.sh example.com [邮箱]

set -e

# 需要 root:下面的系统级改动都直接执行,不再逐条 sudo
if [ "$(id -u)" -ne 0 ]; then
    echo '[!] 这个脚本需要 root 权限,请用 sudo 重新运行:'
    echo '    curl -fsSL 脚本地址 | sudo bash'
    echo '    或已经下载到本地:sudo bash 本文件'
    exit 1
fi

DOMAIN="$1"
EMAIL="$2"

if [ -z "$DOMAIN" ]; then
    echo '用法:bash certbot-ssl.sh <域名> [邮箱]'
    echo '  例:bash certbot-ssl.sh blog.example.com me@example.com'
    exit 1
fi

echo "====== 为 $DOMAIN 申请证书 ======"

if ! command -v nginx >/dev/null 2>&1; then
    echo '[!] 没检测到 Nginx,先跑 nginx-install.sh'
    exit 1
fi

if ! command -v certbot >/dev/null 2>&1; then
    echo '[*] 安装 certbot...'
    if command -v apt-get >/dev/null 2>&1; then
        apt-get update -qq
        apt-get install -y certbot python3-certbot-nginx
    elif command -v dnf >/dev/null 2>&1; then
        dnf install -y certbot python3-certbot-nginx
    else
        echo '[!] 认不出包管理器,装不了 certbot'
        exit 1
    fi
fi

if [ -n "$EMAIL" ]; then
    certbot --nginx -d "$DOMAIN" -m "$EMAIL" --agree-tos --no-eff-email --redirect
else
    echo '[*] 没给邮箱,用 --register-unsafely-without-email'
    echo '    这样收不到到期提醒,建议还是给一个'
    certbot --nginx -d "$DOMAIN" --register-unsafely-without-email --agree-tos --redirect
fi

echo ''
echo '====== 续期演练(只验证,不会真的续)======'
certbot renew --dry-run

下载原始文件