haproxy 设置 https 证书

2020年3月9日 0 条评论 1.58k 次阅读 0 人点赞

haproxy在使用https模式的时候,需要设置证书,这样后端服务器可以使用http服务,对用户来说是个半程的https访问。(没仔细测试后端的https,这样就是全程2段的https)

frontend https-in
    mode http
    bind *:443 ssl crt /etc/haproxy/example.com.pem
    #maxconn 65535
    option forwardfor
    option originalto
    option httpclose
    reqadd X-Forwarded-Proto:\ https
    acl excample_com hdr_dom(host) -i example.com
    use_backend http_backend if excample_com
    default_backend http_backend

backend http_backend
    mode http
    balance source
    server server_A 1.1.1.1:80 maxconn 20480 weight 50 rise 2 fall 3 check inter 2000
    server server_B 1.1.1.1:80 maxconn 20480 weight 50 rise 2 fall 3 check inter 2000

对于使用 acmesh 申请来自于 letsencrypt.org 的证书文件夹,通常包含如下:

example.com.cer
example.com.csr
example.com.key
fullchain.cer
ca.cer

组成 haproxy 所使用的证书格式 example.com.pem ,使用了 fullchain.cer 和 example.com.key :

echo -e "$(cat /etc/haproxy/fullchain.cer)\n\n$(cat /etc/haproxy/example.com.key)
" > /etc/haproxy/example.com.pem

注意:如果证书有更新,haproxy需要重载或者重启,否则haproxy启动之后一直使用的是启动时的那个证书状态

附:使用 lnmp.org 泛域名证书(参考)推送至 haproxy 脚本

#!/bin/bash
path0=$(cd "$(dirname "$0")";pwd)
domain="$1"
remotehost=youhost
sslfilepath="/usr/local/nginx/conf/ssl/"
fullchainfile=${sslfilepath}${domain}/fullchain.cer
keyfile=${sslfilepath}${domain}/${domain}.key
newpemfile=${sslfilepath}${domain}/${domain}.pem
oldpemfile=${sslfilepath}${domain}/${domain}.pem.old

[ ! -f ${oldpemfile} ] && cat ${newpemfile} > ${oldpemfile}

function errorSend() {
    echo "$1" 
}

#generate new pem
if [[ -f "${fullchainfile}" && -f "${keyfile}" ]];then
    echo -e "$(cat ${fullchainfile})\n\n$(cat ${keyfile})" > ${newpemfile}
else
    #file missing 
    errorSend "${HOSTNAME} missing file $([ ! -f ${fullchainfile} ] && echo ${fullchainfile##*/}) $([ ! -f ${keyfile} ] && echo ${keyfile##*/})"
    exit 1
fi
oldmd5=$(/usr/bin/md5sum ${oldpemfile} | awk '{print $1}')
newmd5=$(/usr/bin/md5sum ${newpemfile} | awk '{print $1}')
if [ "${oldmd5}" != "${newmd5}" ];then
    msg="${HOSTNAME} "
    /usr/bin/rsync -avzu -e 'ssh -p22' ${newpemfile} ${remotehost}:/etc/haproxy/ >> ${path0}/rsync_ssl.log 2>&1
    [ $? == 0 ] && msg=${msg}"cer send success. " || msg=${msg}"cer send failed! "
    /usr/bin/ssh -p22 root@${remotehost} 'service haproxy restart' >> ${path0}/rsync_ssl.log 2>&1
    [ $? == 0 ] && msg=${msg}"haproxy reload success. " || msg=${msg}"haproxy reload failed! "
    cat ${newpemfile} > ${oldpemfile}
    tgSend "${msg}"
fi

Sevenfal

这个人太懒什么东西都没留下

文章评论(0)