使用acme.sh脚本自动申请更新泛域名证书

本文最后更新于 2024年7月24日 上午

本文介绍了如何使用acme.sh脚本自动申请和更新泛域名证书。由于免费证书的有效期缩短至3个月,频繁的证书更新变得繁琐。通过acme.sh脚本,可以简化这一过程,实现自动化管理。文章详细讲解了脚本的安装、证书申请、证书安装以及nginx配置等步骤,并提供了相关命令和配置示例。此外,还介绍了脚本的升级和停止证书续订的方法。

前段时间免费证书由1年改成了3个月,我的子域名挺多的,隔三岔五就收到证书要过期的通知,挺烦,但是现在找到了能一劳永逸的工具啦!

1 安装

通过网络请求安装:

1
curl https://get.acme.sh | sh -s email=my@example.com

通过github安装:

1
curl https://raw.githubusercontent.com/acmesh-official/acme.sh/master/acme.sh | sh -s -- --install-online -m  my@example.com

通过git克隆安装:

1
2
3
git clone --depth 1 https://github.com/acmesh-official/acme.sh.git
cd acme.sh
./acme.sh --install -m my@example.com

需要将my@example.com改成自己的邮箱,脚本会被安装到~/.acme.sh/目录中

然后在环境变量中创建别名:

1
2
3
vim ~/.bashrc
# 添加
alias acme.sh=~/.acme.sh/acme.sh

重载环境变量

1
source ~/.bashrc

2 申请证书

这里使用dnsapi的方式申请证书,其他方式见文末的链接。dnsapi支持的平台见此。首先去腾讯云DNSPOD创建密匙,记录下IDtoken两个参数。
在执行脚本的服务器添加环境变量:

1
2
export DP_Id="<id>"
export DP_Key="<token>"

然后申请证书:

1
acme.sh --issue --dns dns_dp -d example.com -d *.example.com

此命令将会申请主域名和泛域名的证书,DP_Id 和DP_Key会被保存到~/.acme.sh/account.conf,之后就不需要再设置了。
执行命令后,还会设置crontab的定时任务,用于更新证书,可以通过命令crontab -l查看到:

1
7 19 * * * "/root/.acme.sh"/acme.sh --cron --home "/root/.acme.sh" > /dev/null

3 安装证书

证书默认保存到脚本安装目录~/.acme.sh/,官方文档建议不要直接使用这里面的,如果仍然想用则,
ssl_certificate对应~/.acme.sh/example.com_ecc/fullchain.cer
ssl_certificate_key对应~/.acme.sh/example.com_ecc/example.com.key

正规方式是将其复制到其他地方使用,脚本提供了--installcert来实现。

1
2

acme.sh --installcert -d example.com --ecc --key-file /root/auto_https_nginx/example.com.key --fullchain-file /root/auto_https_nginx/fullchain.cer --reloadcmd "service nginx force-reload"

nginx配置:

1
vim /etc/nginx/sites-available/example.com

填入:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
server {
listen 80;
server_name abc.example.com;

# Redirect HTTP to HTTPS
location / {
return 301 https://$host$request_uri;
}
}

server {
listen 443 ssl;
server_name abc.example.com;

ssl_certificate /root/auto_https_nginx/fullchain.cer;
ssl_certificate_key /root/auto_https_nginx/example.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;

location / {
proxy_pass http://localhost:1234;
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;
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}

创建链接:

1
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

检测与重启

1
2
sudo nginx -t
sudo service nginx restart

其他

升级acme.sh

1
2
3
4
5
6
# 手动升级
acme.sh --upgrade
# 自动升级
acme.sh --upgrade --auto-upgrade
# 禁用自动升级
acme.sh --upgrade --auto-upgrade 0

停止证书续订

1
acme.sh --remove -d example.com [--ecc]

链接


使用acme.sh脚本自动申请更新泛域名证书
https://blog.kala.love/posts/95b84a7c/
作者
Lissettecarlr
发布于
2024年6月25日
许可协议