使用acme.sh申请ssl并在nginx配置

2025-06-29T18:35:00

安装acme.sh

中国大陆用户(无法访问github)

  1. git clone https://gitee.com/neilpang/acme.sh.git
  2. cd acme.sh
  3. acme.sh --install -m (你的邮箱)

通用方法

curl https://get.acme.sh | sh -s email=(你的邮箱)

出现以上字样表明安装成功

签发证书

官网上有http方式和dns方式。若使用dns方式且自动验证,可以签发通配符证书,如*.wyywn.site

HTTP方式DNS方式(自动验证)
简单方便,可配置一些无法设置dns记录的域名较复杂,需要到域名解析商获取API Key和ID
只能配置有限域名可签发通配符证书,后新增域名不用再配置

此处使用dns方式自动验证,http方式和dns方式手动验证较简单,可前往官方Wiki查看。

本人域名解析商为腾讯的DNSPod。前往控制台API密钥页面,切换到DNSPod Token栏目(不能使用腾讯云 API 密钥,否则会失败,见使用 dns_dp 自动申请证书时,出现 invalid domain。我一开始也被坑了),点击创建密钥并起名。生成后保存好IDToken

执行

export DP_Id="(你的ID)"
export DP_Key="(你的Token)"

签发通配符证书

acme.sh --issue --dns dns_dp -d (你的主域名) -d *.(你的主域名)

acme.sh --issue --dns dns_dp -d wyywn.site -d *.wyywn.site

输入后会运行较长时间


如图,生成了4个文件,证书获取成功。

复制证书

对于nginx,运行

sh acme.sh --install-cert -d (你的主域名) \
--key-file       (你的nginx根目录)/key.pem  \
--fullchain-file (你的nginx根目录)/cert.pem \
--reloadcmd     "service nginx reload"

务必配置reloadcmd,可自动续签

配置nginx

此时还不能直接访问。要到nignx根目录下,你的配置文件处设置监听配置,将http自动转发到https上。两个server字段分别配置80端口和443端口。配置如下

server {
    listen 80;
    server_name wyywn.site www.wyywn.site;
    return 301 https://$host$request_uri; #将http转发到https
}

server {
    listen 443 ssl;
    server_name wyywn.site www.wyywn.site;

    ssl_certificate cert.pem;
    ssl_certificate_key key.pem;

    …………
}

设置完成后运行service nginx restart,访问http网页发现已经自动跳到https,配置成功。

当前页面是本站的「Baidu MIP」版。发表评论请点击:完整版 »