LetsEncrypt域名认证支持HTTP和DNS两种方式,HTTP配置简单但是需要修改HTTP Server配置,DNS配置复杂需要修改DNS记录。本文简易实现了基于DNS认证实现SSL证书生成的方式,支持泛域名证书,示例中的LetsEncrypt脚本基于https://github.com/Neilpang/acme.sh 二次封装,支持Linode、AliDNS的服务提供商。
1、密钥配置
LINODE_API_KEY 为linode提供的个人API token。
Ali_Key和Ali_Secret是您访问阿里云API的密钥。
2、执行脚本
保存文件为 LetsEncrypt.sh
#/bin/sh
MY_DOMAIN=$1
DNS_PROVIDER=$2
if [[ -z "$MY_DOMAIN" ]] || [[ -z "${DNS_PROVIDER}" ]]; then
echo "Usage: ./LetsEncrypt.sh example.com dns_ali"
exit
fi
# linode dns config
export LINODE_API_KEY="###########################"
# ali dns config
export Ali_Key="###########################"
export Ali_Secret="###########################"
export DOMAIN_PATH="$HOME/.acme.sh/$MY_DOMAIN"
export CERT_KEY_PATH="$DOMAIN_PATH/$MY_DOMAIN.key"
export CERT_PATH="$DOMAIN_PATH/$MY_DOMAIN.cer"
export CERT_FULLCHAIN_PATH="$DOMAIN_PATH/fullchain.cer"
export ACCOUNT_KEY_PATH="$DOMAIN_PATH/account.key"
ACME_SH="https://raw.githubusercontent.com/Neilpang/acme.sh/master/acme.sh"
DNS_SH="https://raw.githubusercontent.com/Neilpang/acme.sh/master/dnsapi/${DNS_PROVIDER}.sh"
TMP_DIR="/tmp/acme.sh/"
if [ -d $TMP_DIR ]
then
rm -rf $TMP_DIR
fi
mkdir -p $TMP_DIR
mkdir -p $TMP_DIR/dnsapi
cd $TMP_DIR
curl $ACME_SH -o acme.sh >/dev/null 2>&1
chmod 755 acme.sh
curl $DNS_SH -o dnsapi/${DNS_PROVIDER}.sh >/dev/null 2>&1
chmod 755 dnsapi/${DNS_PROVIDER}.sh
./acme.sh --issue -d $MY_DOMAIN -d *.$MY_DOMAIN --keylength 4096 --accountkeylength 4096 --dns ${DNS_PROVIDER} --dnssleep 1800 --force --reloadcmd "service nginx force-reload"
3、运行示例
./LetsEncrypt.sh yee.im dns_ali
./LetsEncrypt.sh yee.im dns_linode
4、Nginx配置示例
server {
listen 0.0.0.0:443 ssl http2;
server_name yee.im;
server_tokens off;
ssl_certificate /home/lijun/.ssl/yee.im/yee.im.cer;
ssl_certificate_key /home/lijun/.ssl/yee.im/yee.im.key;
ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;
root /home/lijun/www/yee.im;
location / {
autoindex on;
}
}
5、脚本定时任务
sudo crontab -e
# 每月执行一次
0 0 1 * * /home/lijun/letsencrypt/LetsEncrypt.sh