You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过HAProxy基于域名列表自动生成及续期Let's Encrypt证书?

HAProxy自动生成&续期Let's Encrypt证书方案

当然可以!HAProxy搭配Let's Encrypt的工具链完全能搞定这个需求——你只需要指定好主域名和备用域名(SANs),确保IP解析正确,证书的申请、续期甚至重载HAProxy这些事儿都能自动化完成,不用手动跑命令折腾。

核心思路

咱们用ACME协议客户端(比如acme.sh或Certbot)对接Let's Encrypt,负责证书的申请、续期;客户端会自动把生成的证书部署到HAProxy指定目录,续期成功后自动重载HAProxy让新证书生效。

前提条件

  • 所有目标域名/备用域名的A/AAAA记录已经正确指向HAProxy所在服务器的公网IP(Let's Encrypt需要通过IP访问验证域名归属)
  • HAProxy服务器能正常访问外网(对接Let's Encrypt API需要)

方案一:用acme.sh实现(轻量首选)

acme.sh是个轻量无依赖的ACME客户端,自动续期默认开启,对HAProxy的适配很友好。

1. 安装acme.sh

# 替换成你的邮箱(用于接收证书过期提醒)
curl -s https://get.acme.sh | sh -s email=your-email@example.com

安装完成后,它会自动创建系统定时任务,负责后续的证书续期。

2. 申请证书

推荐用TLS-ALPN-01验证,不需要修改HAProxy的HTTP配置,直接通过443端口完成验证:

# 替换成你的主域名和备用域名,多个域名用-d追加
acme.sh --issue --alpn -d example.com -d www.example.com -d sub.example.com

如果必须用HTTP-01验证,需要先让HAProxy把/.well-known/acme-challenge/路径的请求转发到指定目录,再执行:

# 指定webroot目录(HAProxy转发的目标目录)
acme.sh --issue -d example.com -d www.example.com --webroot /var/www/acme-challenge/

3. 部署证书到HAProxy

申请成功后,把证书部署到HAProxy的证书存储目录(比如/etc/haproxy/certs/),同时配置续期后自动重载HAProxy:

acme.sh --install-cert -d example.com \
--key-file /etc/haproxy/certs/example.com.key \
--fullchain-file /etc/haproxy/certs/example.com.pem \
--reloadcmd "systemctl reload haproxy"

acme.sh会自动把证书和私钥合并成HAProxy需要的PEM格式,后续续期成功后会自动执行重载命令。

方案二:用Certbot实现(官方推荐)

Certbot是Let's Encrypt官方推荐的客户端,功能更全面,有专门的HAProxy插件。

1. 安装Certbot

以Debian/Ubuntu为例:

apt update && apt install certbot python3-certbot-haproxy

2. 申请证书

同样推荐TLS-ALPN-01验证:

# 替换成你的域名列表
certbot certonly --tls-alpn-01-port 443 -d example.com -d www.example.com -d sub.example.com

如果用HTTP-01验证,需要先配置HAProxy转发验证请求到指定目录:

certbot certonly --webroot -w /var/www/acme-challenge/ -d example.com -d www.example.com

3. 配置自动续期重载

Certbot默认会创建定时任务自动续期,我们只需要添加续期成功后重载HAProxy的钩子:

# 编辑对应域名的续期配置
nano /etc/letsencrypt/renewal/example.com.conf

在[renewalparams]区块添加:

renew_hook = systemctl reload haproxy

或者在申请证书时直接指定钩子:

certbot certonly --tls-alpn-01-port 443 -d example.com --renew-hook "systemctl reload haproxy"

验证自动续期

可以手动模拟续期流程,测试是否正常:

# acme.sh测试续期(不会真的续期,仅验证流程)
acme.sh --renew -d example.com --test

# Certbot测试续期
certbot renew --dry-run

内容的提问来源于stack exchange,提问作者shrw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:28:20