前言

反向代理大家用的最多的应该是nginx吧,然后还有caddy,这次来点不一样的,使用haproxy做反向代理。

系统:debian12

使用场景:网站反代

前提:后端站点要配置好证书,绑定域名

域名解析到安装haproxy服务器的ip上

找一台线路还不错的服务器按照以下方式进行

HAProxy的安装

apt install haproxy -y

安装完毕后,启用haproxy进程

systemctl start haproxysystemctl enable haproxy

HAProxy的配置文件地址默认为/etc/haproxy/haproxy.cfg接下来,我们要编辑这个文件,

nano /etc/haproxy/haproxy.cfg

配置HAProxy前后端

反代后端站点的80和443端口,仅修改后端服务器ip即可

提示:8.8.8.8为备用服务器(不需要可以注释掉),要做负载均衡,把backup参数移除

global    log /dev/log    local0    log /dev/log    local1 notice    chroot /var/lib/haproxy    stats socket /run/haproxy/admin.sock mode 660 level admin    stats timeout 30s    user haproxy    group haproxy    daemon    maxconn 30000defaults    log     global    mode    tcp    option  tcplog    option  dontlognull    option  clitcpka    option  srvtcpka    timeout connect 5000    timeout client  50000    timeout server  50000    errorfile 400 /etc/haproxy/errors/400.http    errorfile 403 /etc/haproxy/errors/403.http    errorfile 408 /etc/haproxy/errors/408.http    errorfile 500 /etc/haproxy/errors/500.http    errorfile 502 /etc/haproxy/errors/502.http    errorfile 503 /etc/haproxy/errors/503.http    errorfile 504 /etc/haproxy/errors/504.http# HTTPS重定向frontend (HTTP模式)frontend http_redirect    bind *:80    mode http    option httplog    redirect scheme https code 301# HTTPS frontend (TCP模式用于SSL透传)frontend tcp_front_443    bind *:443    mode tcp    option tcplog    rate-limit sessions 15000    default_backend servers_443backend servers_443    mode tcp    server web1 7.7.7.7:443 check inter 10s rise 2 fall 3    server web2 8.8.8.8:443 check inter 10s rise 2 fall 3 backup

验证格式是否正确:

haproxy -c -f /etc/haproxy/haproxy.cfg

重启生效

systemctl restart haproxy

检查状态

systemctl status haproxy

添加安全头

可选,在后端站点,例如站点nginx配置中添加以下参数

add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;add_header X-Content-Type-Options "nosniff" always;add_header X-XSS-Protection "1; mode=block" always;add_header Referrer-Policy "strict-origin-when-cross-origin" always;