安装nginx

sudo apt update
sudo apt install nginx
sudo systemctl status nginx
一般没有输出明显报错就是成功,安装成功一般也会输出类似以下信息
Jul 08 16:54:50 VM-0-7-ubuntu systemd[1]: Starting A high performance web server and a reverse proxy server..

Nginx配置修改

  • sudo vi /etc/nginx/sites-available/default 添加80/443端口 443指定安装证书路径 可以先配置上 becool.vip替换为自己的域名 root路径替换为自己的hugo静态网站路径
server {
    listen 80;
    server_name becool.vip;
    root /home/ubuntu/blog/public;
    index index.html;
    location / {
        try_files $uri $uri/ =404;
    }
}
server {
    listen 443 ssl;
    server_name becool.vip;
    ssl_certificate /etc/letsencrypt/live/becool.vip/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/becool.vip/privkey.pem;
    root /home/ubuntu/blog/public;
    index index.html;
    location / {
        try_files $uri $uri/ =404;
    }
}

安装Certbot

sudo apt-get install certbot

申请证书

  • 注意替换自己的域名 申请成功会默认放在/etc/letsencrypt/live/目录 也会打印证书和privkey文件的路径 跟/etc/nginx/sites-available/default 里面的路径核对下是否一致 不一致就修改下/etc/nginx/sites-available/default里面的路径
  • 调用命令之前注意先停掉nginx
sudo certbot certonly --standalone -d becool.vip -d www.becool.vip --email your@email.com --agree-tos --no-eff-email --force-renewal

启动脚本定时监控续期

脚本内容

  • 默认提前5天续期 可自行修改
# 定义证书存储目录
certs_directory="/etc/letsencrypt/live/"
days_before_expiry=5  # 设置在证书到期前几天触发续签
# 遍历所有证书文件
for cert_dir in $certs_directory*; do
    # 获取域名
    domain=$(basename "$cert_dir")
    # 忽略 README 目录
    if [ "$domain" = "README" ]; then
        continue
    fi
    # 输出正在检查的证书信息
    echo "检查证书过期日期: ${domain}"
    # 获取fullchain.pem文件路径
    cert_file="${cert_dir}/fullchain.pem"
    # 获取证书过期日期
    expiration_date=$(openssl x509 -enddate -noout -in "${cert_file}" | cut -d "=" -f 2-)
    # 输出证书过期日期
    echo "过期日期: ${expiration_date}"
    # 将日期转换为时间戳
    expiration_timestamp=$(date -d "${expiration_date}" +%s)
    current_timestamp=$(date +%s)
    # 计算距离过期还有几天
    days_until_expiry=$(( ($expiration_timestamp - $current_timestamp) / 86400 ))
    # 检查是否需要续签(在满足续签条件的情况下)
    if [ $days_until_expiry -le $days_before_expiry ]; then
        echo "证书将在${days_before_expiry}天内过期,正在进行自动续签。"
        # 停止 Nginx
        sudo systemctl stop nginx
        iptables -P INPUT ACCEPT
        iptables -P FORWARD ACCEPT
        iptables -P OUTPUT ACCEPT
        iptables -F
        ip6tables -P INPUT ACCEPT
        ip6tables -P FORWARD ACCEPT
        ip6tables -P OUTPUT ACCEPT
        ip6tables -F
        # 续签证书
        certbot certonly --standalone -d $domain -d "www.$domain" --email your@email.com --agree-tos --no-eff-email --force-renewal
        # 启动 Nginx
        sudo systemctl start nginx
        echo "证书已成功续签。"
    else
        # 若未满足续签条件,则输出证书仍然有效
        echo "证书仍然有效,距离过期还有 ${days_until_expiry} 天。"
    fi
    # 输出分隔线
    echo "--------------------------"
done

配置crontab自动执行

  • 每天执行一次
0 0 * * * sudo /home/ubuntu/shell/auto_cert_renewal.sh >/home/ubuntu/shell/auto_cert_renewal.sh.log