一、负载均衡
1.1负载均衡的定义
负载均衡是一种将网络流量或计算任务分配到多个服务器、网络链路或其他资源的策略,旨在优化资源使用、最大化吞吐量、最小化响应时间,并避免单点故障。通过分散工作负载,系统可以提升整体性能和可靠性。
将用户的请求通过LB调度器分散到多台后端服务器中,每个主机承担一些以减小每个服务器主机的压力,就像一根钢缆由许多根钢丝组成,每根钢丝将力分担了钢缆也就能承载更大的负载。
1.2那为什么要用负载均衡?
负载均衡的作用:通过合理分配网络流量或计算任务,优化资源使用效率,提升系统整体性能和可靠性。
优点:
Web服务器的动态水平扩展-->对用户无感知
增加业务并发访问及处理能力-->解决单服务器瓶颈问题
节约公网IP地址-->降低IT支出成本
隐藏内部服务器IP-->提高内部服务器安全性
配置简单-->固定格式的配置文件
功能丰富-->支持四层和七层,支持动态下线主机
性能较强-->并发数万甚至数十万
以下是其核心价值:
提升性能
将用户请求分散到多个服务器,避免单一服务器过载,降低响应延迟,提高吞吐量。例如,电商网站在大促时通过负载均衡分担流量压力。
增强可用性
当某台服务器故障时,自动将流量转移到健康节点,确保服务不间断。例如,金融系统通过负载均衡实现故障自动切换,减少宕机影响。
扩展性支持
动态添加或移除服务器时,负载均衡自动调整流量分配,适应业务增长或收缩。云计算环境中常结合弹性伸缩服务实现资源动态调配。
优化资源利用
根据服务器负载情况(如CPU、内存使用率)智能分配请求,避免资源浪费。例如,视频处理平台将任务优先分配给空闲的计算节点。
安全防护
结合反向代理隐藏后端服务器IP,抵御DDoS攻击。部分负载均衡器还提供SSL卸载、流量过滤等功能。
1.3负载均衡类型
四层负载均衡(传输层)
基于IP和端口进行流量分发,如LVS、AWS Network Load Balancer。处理速度快,适用于TCP/UDP协议,但对应用层内容无感知。
1.通过ip+port决定负载均衡的去向。
2.对流量请求进行NAT处理,转发至后台服务器。
3.记录tcp、udp流量分别是由哪台服务器处理,后续该请求连接的流量都通过该服务器处理。
4.支持四层的软件
lvs:重量级四层负载均衡器。
Nginx:轻量级四层负载均衡器,可缓存。(nginx四层是通过upstream模块)
Haproxy:模拟四层转发。
七层负载均衡(应用层)
解析HTTP/HTTPS协议内容,按URL、Cookie等规则分发。如Nginx、ALB(AWS Application Load Balancer),支持更细粒度的路由和灰度发布。
1.通过虚拟ur|或主机ip进行流量识别,根据应用层信息进行解析,决定是否需要进行负载均衡。
2.代理后台服务器与客户端建立连接,如nginx可代理前后端,与前端客户端tcp连接,与后端服务器建立 tcp连接。
3.支持7层代理的软件:
Nginx:基于http协议(nginx七层是通过proxy_pass)
Haproxy:七层代理,会话保持、标记、路径转移等。
四层与七成负载均衡的区别
所谓的四到七层负载均衡,就是在对后台的服务器进行负载均衡时,依据四层的信息或七层的信息来决定怎么样转发流量.
四层的负载均衡,就是通过发布三层的IP地址(VIP),然后加四层的端口号,来决定哪些流量需要做负 载均衡,对需要处理的流量进行NAT处理,转发至后台服务器,并记录下这个TCP或者UDP的流量是由哪 台服务器处理的,后续这个连接的所有流量都同样转发到同一台服务器处理. 它就像是快递公司只看地址送包裹,简单、快速、成本低,适合简单场景。
简而言之
四层负载均衡就像是快递公司只看地址送包裹,简单、快速、成本低,适合简单场景。
七层负载均衡就像是快递公司不仅看地址,还会打开包裹检查内容,然后根据内容送到更合适的仓
库,功能强大、复杂、成本高,适合复杂场景。
分层位置:四层负载均衡在传输层及以下,七层负载均衡在应用层及以下
性能 :四层负载均衡架构无需解析报文消息内容,在网络吞吐量与处理能力上较高;
七层可支持解析应用 层报文消息内容,识别URL、Cookie、HTTP header等信息。
原理 :四层负载均衡是基于ip+port;七层是基于虚拟的URL或主机IP等。
功能类比:四层负载均衡类似于路由器;七层类似于代理服务器。
安全性:四层负载均衡无法识别DDoS攻击;七层可防御SYN Cookie/Flood攻击
二、haproxy
HAProxy(High Availability Proxy)是一款开源的高性能TCP/HTTP负载均衡器,它主要用于提高网站、应用或服务的可用性和性能。HAProxy在负载均衡领域非常受欢迎,被广泛应用于各种规模的互联网项目中。
2.1、haproxy安装
实验环境
功能 | IP |
客户端client | eth0:192.16.217.111 |
haproxy | eth0:192.168.217.100,eth1:172.168.217.10 |
RS1 | eth0:172.168.217.10 |
RS2 | eth0:172.168.217.20 |
在RS1和RS2上的配置
能互相curl通也能ping通
harpoxy配置
软件安装,关闭防火墙和seliux
[root@haproxy ~]# yum install haproxy -y
2.2haproxy基本信息
软件安装包: haproxy-2.4.22-3.el9_3.x86_64.rpm
启动文件: /lib/systemd/system/haproxy.service
主配置目录: /etc/haproxy/
主配置文件: /etc/haproxy/haproxy.cfg
子配置目录: /etc/haproxy/conf.d
harpoxy配置基本信息
HAProxy 的配置文件haproxy.cfg由两大部分组成,分别是:
global:全局配置段
进程及安全配置相关的参数
性能调整相关参数
Debug参数
proxies:代理配置段
defaults:为frontend, backend, listen提供默认配置
frontend:前端,相当于nginx中的server {}
backend:后端,相当于nginx中的upstream {}
listen:同时拥有前端和后端配置,配置简单,生产推荐使用
global全局参数说明
global
log 127.0.0.1 local2 #定义全局的syslog服务器;日志服务器需要开启UDP协议最多可以定义两个
chroot /var/lib/haproxy #锁定运行目录
pidfile /var/run/haproxy.pid #指定pid文件
maxconn 100000 #指定最大连接数
user haproxy #指定haproxy的运行用户
group haproxy #指定haproxy的运行组
daemon #指定haproxy以守护进程方式运行
# turn on stats unix socket
stats socket /var/lib/haproxy/stats #指定haproxy的套接字文件
nbproc 2 #指定haproxy的work进程数量,默认是1个
cpu-map 1 0 #指定第一个work绑定第一个cpu核心
cpu-map 2 1 #指定第二个work绑定第二个cpu核心
nbthread 2 #指定haproxy的线程数量,默认每个进程一个线程,此参数与nbproc互斥
maxsslconn 100000 #每个haproxy进程ssl最大连接数,用于haproxy配置了证书的场景下
maxconnrate 100 #指定每个客户端每秒建立连接的最大数量
多进程和多线程配置
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面内容省略...
global
log 127.0.0.1 local2
chroot /var/lib/haproxy
pidfile /var/run/haproxy.pid
maxconn 100000
user haproxy
group haproxy
daemon
# turn on stats unix socket
stats socket /var/lib/haproxy/haproxy.sock1 mode 600 level admin process 1 #启用多个sock文件
stats socket /var/lib/haproxy/haproxy.sock2 mode 600 level admin process 2
#多进程:
nbproc 2 #启用多进程
cpu-map 1 0 #进程和cpu核心绑定防止cpu抖动从而减少系统资源消耗
cpu-map 2 1 #2 表示第二个进程,1表示第二个cpu核心
###多线程
nbthread 2 #启用多线程
查看多进程信息
pstree -p | grep haproxy
多线程对比
#使用以下命令查询到子进程id号
ps -ef | grep haproxy | grep -v grep
未开启多线程
haproxy ~]# cat /proc/xxxx(haproxy子进程id)/status
...上面内容省略...
Threads: 1
...下面内容省略...
开启后
haproxy ~]# cat /proc/xxxx(haproxy子进程id)/status
...上面内容省略...
Threads: 2
...下面内容省略...
proxies配置
参数
|
类型 | 作用 |
defaults | proxies |
默认配置项,针对以下的frontend、backend和listen生效,可以多个
name也可以没有name
|
frontend | proxies |
前端servername,类似于Nginx的一个虚拟主机 server和LVS服务集
群。
|
backend
|
proxies |
#后端服务器组,等于nginx的upstream和LVS中的RS服务器
|
listen | proxies |
#将frontend和backend合并在一起配置,相对于frontend和backend
配置更简洁,生产常用
|
注意:
defaults参数
defaults
mode http #HAProxy实例使用的连接协议
log global #指定日志地址和记录日志条目的syslog/rsyslog日志设备
#此处的 global表示使用 global配置段中设定的log值。
option httplog #日志记录选项,httplog表示记录与 HTTP会话相关的各种属性值
#包括 HTTP请求、会话状态、连接数、源地址以及连接时间等
option dontlognull #dontlognull表示不记录空会话连接日志
option http-server-close #等待客户端完整HTTP请求的时间,此处为等待10s。
option forwardfor except 127.0.0.0/8 #透传客户端真实IP至后端web服务器
#在apache配置文件中加入:<br>%{XForwarded-For}i
#后在webserver中看日志即可看到地址透传信息
option redispatch #当server Id对应的服务器挂掉后,强制定向到其他健康的服务器,重新派发
option http-keep-alive #开启与客户端的会话保持
retries 3 #连接后端服务器失败次数
timeout http-request 10s #等待客户端请求完全被接收和处理的最长时间
timeout queue 1m #设置删除连接和客户端收到503或服务不可用等提示信息前的等待时间
timeout connect 120s #设置等待服务器连接成功的时间
timeout client 600s #设置允许客户端处于非活动状态,即既不发送数据也不接收数据的时间
timeout server 600s #设置服务器超时时间,即允许服务器处于既不接收也不发送数据的非活动时间
timeout http-keep-alive 60s #session 会话保持超时时间,此时间段内会转发到相同的后端服务器
timeout check 10s #指定后端服务器健康检查的超时时间
maxconn 10000
default-server inter 1000 weight 3
frontend 配置参数
bind:指定HAProxy的监听地址,可以是IPV4或IPV6,可以同时监听多个IP或端口,可同时用于listen字 段中#格式:bind [<address>]:<port_range> [, ...] [param*]#注意:如果需要绑定在非本机的IP,需要开启内核参数:net.ipv4.ip_nonlocal_bind=1backlog <backlog> #针对所有server配置,当前端服务器的连接数达到上限后的后援队列长度,注意:不 支持backend
配置示例
测试
backend配置
mode http|tcp #指定负载协议类型,和对应的frontend必须一致
option #配置选项
server #定义后端real server,必须指定IP和端口
注意:option后面加 httpchk,smtpchk,mysql-check,pgsql-check,ssl-hello-chk方法,可用于实现更
多应用层检测功能
#针对一个server配置
check #对指定real进行健康状态检查,如果不加此设置,默认不开启检查,只有check后面没有其它配置也可以启用检查功能
#默认对相应的后端服务器IP和端口,利用TCP连接进行周期性健康性检查,注意必须指定端口才能实现健康性检查
addr <IP> #可指定的健康状态监测IP,可以是专门的数据网段,减少业务网络的流量
port <num> #指定的健康状态监测端口
inter <num> #健康状态检查间隔时间,默认2000 ms
fall <num> #后端服务器从线上转为线下的检查的连续失效次数,默认为3
rise <num> #后端服务器从下线恢复上线的检查的连续有效次数,默认为2
weight <weight> #默认为1,最大值为256,0(状态为蓝色)表示不参与负载均衡,但仍接受持久连接
backup #将后端服务器标记为备份状态,只在所有非备份主机down机时提供服务,类似Sorry
Server
disabled #将后端服务器标记为不可用状态,即维护状态,除了持久模式
#将不再接受连接,状态为深黄色,优雅下线,不再接受新用户的请求
redirect prefix http://www.baidu.com/ #将请求临时(302)重定向至其它URL,只适用于http模
式
maxconn <maxconn> #当前后端server的最大并发连接数
配置示例
测试
配置sorry_server
在haproxy主机上配置
将RS1和RS2 nginx服务stop然后再访问haproxy就会走sorry server
关于disabled
socat 工具

#查看帮助
haproxy ~]# socat -h
haproxy ~]# echo "help" | socat stdio /var/lib/haproxy/stats
The following commands are valid at this level:
help : this message
prompt : toggle interactive mode with prompt
quit : disconnect
。。。省略 。。。
enable server : enable a disabled server (use 'set server' instead) #启用服务器
set maxconn server : change a server's maxconn setting
set server : change a server's state, weight or address #设置服务器
get weight : report a server's current weight #查看权重
常用示例:
set weight : change a server's weight (deprecated) #设置权重
show startup-logs : report logs emitted during HAProxy startup
how peers [peers section]: dump some information about all the peers or this
peers section
set maxconn global : change the per-process maxconn setting
set rate-limit : change a rate limiting value
set severity-output [none|number|string] : set presence of severity level in
feedback information
set timeout : change a timeout setting
show env [var] : dump environment variables known to the process
show cli sockets : dump list of cli sockets
。。。省略 。。。
echo "show info" | socat stdio /var/lib/haproxy/stats

[root@haproxy ~]# echo "show servers state" | socat stdio /var/lib/haproxy/stats
[root@haproxy ~]# echo get weight webcluster/web1 | socat stdio
/var/lib/haproxy/stats
2 (initial 2)
[root@haproxy ~]# echo get weight webcluster/web2 | socat stdio
/var/lib/haproxy/stats
1 (initial 1)
[root@haproxy ~]# echo "set weight webserver/web1 1 " | socat stdio
/var/lib/haproxy/stats
[root@haproxy ~]# echo "set weight webserver/web1 2 " | socat stdio
/var/lib/haproxy/stats
#下线后端服务器
[root@haproxy ~]# echo "disable server webserver/web1 " | socat stdio
/var/lib/haproxy/stats
#上线后端服务器
[root@haproxy ~]# echo "enable server webserver/web1 " | socat stdio
/var/lib/haproxy/stats
多进程热处理


三、高级功能及配置
3.1、基于cookie的会话保持(不支持tcp)
listen webserver
bind *:80
mode http
balance roundrobin
cookie WEBCOOKIE nocache indirect
server web1 192.168.217.10:80 cookie web1 check inter 3s fall 5 rise 3 weight 1
server web2 192.168.217.20:80 cookie web2 check inter 3s fall 5 rise 3 weight 1
3.2、haproxy的状态界面
通过web界面,显示当前HAProxy的运行状态
配置
#---------------------------------------------------------------------
listen stats:
mode http
bind *:8888
stats enable
log global
stats uri /stats
stats auth lee:lee
#---------------------------------------------------------------------
stats enable #基于默认的参数启用stats pagestats hide-version #将状态页中haproxy版本隐藏stats refresh <delay> #设定自动刷新时间间隔,默认不自动刷新stats uri <prefix> #自定义stats page uri,默认值:/haproxy?statsstats auth <user>:<passwd> #认证时的账号和密码,可定义多个用户,每行指定一个用户#默认:no authenticationstats admin { if | unless } <cond> #启用stats page中的管理功能
3.3、IP透传
3.3.1 四层IP透传
在后端服务器上配置(RS1和RS2)
#nginx 配置:在访问日志中通过变量$proxy_protocol_addr 记录透传过来的客户端IP
在haproxy上配置
listen webserver
bind *:80
mode tcp
balance roundrobin
server web1 192.168.217.10:80 send-proxy check inter 3s fall 5 rise 3 weight 1
server web2 192.168.217.20:80 send-proxy check inter 3s fall 5 rise 3 weight 1
没开启前
开启后
3.3.2七层透传
option forwardfor [ except <network> ] [ header <name> ] [ if-none ][ except <network> ]:请求报请来自此处指定的网络时不予添加此首部,如haproxy自身所在网络[ header <name> ]: 使用自定义的首部名称,而非“X-Forwarded-For",示例:X-client[ if-none ] 如果没有首部才添加首部,如果有使用默认值
listen webserver
bind *:80
option forwardfor
mode http
balance roundrobin
server web1 192.168.217.10:80 send-proxy check inter 3s fall 5 rise 3 weight 1
server web2 192.168.217.20:80 send-proxy check inter 3s fall 5 rise 3 weight 1
3.4ACL
在 HAProxy 中,acl
(Access Control List)是 条件判断 的核心指令,用于根据请求特征(URL、Header、源 IP、Cookie 等)做 路由、限制、重写 等决策。
3.4.1、ACL配置选项
#用acl来定义或声明一个acl
acl <aclname> <criterion> [flags] [operator] [<value>]
acl 名称 匹配规范 匹配模式 具体操作符 操作对象类型
3.4.2、ACL-Name 名称
acl test path_end -m sub /a
#ACL名称,可以使用大字母A-Z、小写字母a-z、数字0-9、冒号:、点.、中横线和下划线,并且严格区分大
小写,比如:my_acl和My_Acl就是两个完全不同的acl5.8.1.2 ACL-criterion
frontend webserver
bind *:80
mode http
# acl test hdr_dom(host) -i www.timinglee.org
acl test path_end -m sub /a
use_backend webservera if test
default_backend webserverb
backend webservera
balance roundrobin
server web1 192.168.217.10:80 check inter 3s fall 5 rise 3
backend webserverb
server web2 192.168.217.20:80 check inter 3s fall 5 rise 3
3.4.3、ACL-criterion 匹配规范
hdr string,提取在一个HTTP请求报文的首部
hdr([<name> [,<occ>]]):完全匹配字符串,header的指定信息,<occ> 表示在多值中使用的值的出现次数
hdr_beg([<name> [,<occ>]]):前缀匹配,header中指定匹配内容的begin
hdr_end([<name> [,<occ>]]):后缀匹配,header中指定匹配内容end
hdr_dom([<name> [,<occ>]]):域匹配,header中的dom(host)
hdr_dir([<name> [,<occ>]]):路径匹配,header的uri路径
hdr_len([<name> [,<occ>]]):长度匹配,header的长度匹配
hdr_reg([<name> [,<occ>]]):正则表达式匹配,自定义表达式(regex)模糊匹配
hdr_sub([<name> [,<occ>]]):子串匹配,header中的uri模糊匹配 模糊匹配c 报文中a/b/c也会匹配
示例:
hdr(<string>) 用于测试请求头部首部指定内容
hdr_dom(host) 请求的host名称,如 www.timinglee.org
hdr_beg(host) 请求的host开头,如 www. img. video. download. ftp.
hdr_end(host) 请求的host结尾,如 .com .net .cn
访问www.timinglee.org,是就去到10,不是就去到20
(要在client上做haproxy的域名解析 让他知道www.timinglee.org是haproxy)
frontend webserver
bind *:80
mode http
acl test hdr_dom(host) -i www.timinglee.org
use_backend webservera if test
default_backend webserverb
backend webservera
balance roundrobin
server web1 192.168.217.10:80 check inter 3s fall 5 rise 3
backend webserverb
server web2 192.168.217.20:80 check inter 3s fall 5 rise 3
访问host以什么结尾
frontend webserver
bind *:80
mode http
acl test hdr_end(host) -i .com .c .net .org
use_backend webservera if test
default_backend webserverb
backend webservera
balance roundrobin
server web1 192.168.217.10:80 check inter 3s fall 5 rise 3
backend webserverb
server web2 192.168.217.20:80 check inter 3s fall 5 rise 3
拒绝是curl的User-Anget请求头
curl -A
用来自定义发送给服务器的 User-Agent
请求头。
frontend webserver
bind *:80
mode http
acl test hdr_end(host) -i .com .c .net .org
acl bad_agent hdr_sub(User-Agent) -i curl
use_backend webservera if test
default_backend webserverb
http-request deny if bad_agent
backend webservera
balance roundrobin
server web1 192.168.217.10:80 check inter 3s fall 5 rise 3
backend webserverb
server web2 192.168.217.20:80 check inter 3s fall 5 rise 3
#有些功能是类似的,比如以下几个都是匹配用户请求报文中host的开头是不是www
acl short_form hdr_beg(host) www.
acl alternate1 hdr_beg(host) -m beg www.
acl alternate2 hdr_dom(host) -m beg www.
acl alternate3 hdr(host) -m beg www.
base : string
#返回第一个主机头和请求的路径部分的连接,该请求从主机名开始,并在问号之前结束,对虚拟主机有用
<scheme>://<user>:<password>@#<host>:<port>/<path>;<params>#?<query>#<frag>
base : exact string match
base_beg : prefix match
base_dir : subdir match
base_dom : domain match
base_end : suffix match
base_len : length match
base_reg : regex match
base_sub : substring match
path : string
#提取请求的URL路径,该路径从第一个斜杠开始,并在问号之前结束(无主机部分)
<scheme>://<user>:<password>@<host>:<port>#/<path>;<params>#?<query>#<frag>
path : exact string match
path_beg : prefix match #请求的URL开头,如/static、/images、/img、/css
path_end : suffix match #请求的URL中资源的结尾,如 .gif .png .css .js .jpg .jpeg
path_dom : domain match
path_dir : subdir match
path_len : length match
path_reg : regex match
path_sub : substring match
#示例:
path_beg -i /haproxy-status/
path_end .jpg .jpeg .png .gif
path_reg ^/images.*\.jpeg$
path_sub image
path_dir jpegs
path_dom timinglee
url : string
#提取请求中的整个URL。
url :exact string match
url_beg : prefix match
url_dir : subdir match
url_dom : domain match
url_end : suffix match
url_len : length match
url_reg : regex match
url_sub : substring match
dst #目标IP
dst_port #目标PORT
src #源IP
src_port #源PORT
#示例:
acl invalid_src src 10.0.0.7 192.168.1.0/24
acl invalid_src src 172.16.0.0/24
acl invalid_port src_port 0:1023
status : integer #返回在响应报文中的状态码
#七层协议
acl valid_method method GET HEAD
http-request deny if ! valid_method
ACL匹配模式
-i 不区分大小写-m 使用指定的正则表达式匹配方法-n 不做DNS解析-u 禁止acl重名,否则多个同名ACL匹配或关系
整数比较:eq、ge、gt、le、lt
字符比较:
- exact match (-m str) :字符串必须完全匹配模式
- substring match (-m sub) :在提取的字符串中查找模式,如果其中任何一个被发现,ACL将匹配
- prefix match (-m beg) :在提取的字符串首部中查找模式,如果其中任何一个被发现,ACL将匹配
- suffix match (-m end) :将模式与提取字符串的尾部进行比较,如果其中任何一个匹配,则ACL进行
匹配
- subdir match (-m dir) :查看提取出来的用斜线分隔(“/")的字符串,如其中任一个匹配,则ACL
进行匹配
- domain match (-m dom) :查找提取的用点(“.")分隔字符串,如果其中任何一个匹配,则ACL进行
匹配
ACL-value 操作对象
The ACL engine can match these types against patterns of the following types :
- Boolean #布尔值
- integer or integer range #整数或整数范围,比如用于匹配端口范围
- IP address / network #IP地址或IP范围, 192.168.0.1 ,192.168.0.1/24
- string--> www.timinglee.org
exact #精确比较
substring #子串
suffix #后缀比较
prefix #前缀比较
subdir #路径, /wp-includes/js/jquery/jquery.js
domain #域名,www.timinglee.org
- regular expression #正则表达式
- hex block #16进制
与:隐式(默认)使用
或:使用“or" 或 “||"表示
否定:使用 "!" 表示
#示例:
if valid_src valid_port #与关系,ACL中A和B都要满足为true,默认为与
if invalid_src || invalid_port #或,ACL中A或者B满足一个为true
if ! invalid_src #非,取反,不满足ACL才为true
拒绝指定IP或者范围
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面内容省略...
frontend testacl
bind :80
mode http
########### ACL settings #######################
acl web_host hdr_dom(host) www.timinglee.org
########### host ###########################
use_backend timinglee_host if web_host
########### default server ###################
default_backend default_webserver
backend timinglee_host
mode http
server web1 192.168.0.101:80 check weight 1 inter 3s fall 3 rise 5
server web2 192.168.0.102:80 check weight 1 inter 3s fall 3 rise 5
backend default_webserver
mode http
server web1 172.25.254.10:80 check weight 1 inter 3s fall 3 rise 5
#测试结果
[root@node10 html]# curl www.timinglee.org
RS1 192.168.217.10
[root@node10 html]# curl www.timinglee.org
RS2 server - 192.168.217.20
[root@node10 html]# curl 192.168.217.100
default web server node10
haproxy ~]# vim /etc/haproxy/haproxy.cfg
frontend testacl
bind :80
mode http
########### ACL settings #######################
acl ip_test src 172.168.217.1 192.168.0.0/24
########### host ###########################
use_backend ip_test-host if ip_test
########### default server ###################
default_backend default_webserver
backend ip_test-host
mode http
server web1 192.168.217.10:80 check weight 1 inter 3s fall 3 rise 5
backend default_webserver
mode http
server web1 172.217.168.10:80 check weight 1 inter 3s fall 3 rise 5
haproxy ~]# vim /etc/haproxy/haproxy.cfg
frontend testacl
bind :80
mode http
########### ACL settings #######################
acl web_host hdr_dom(host) www.timinglee.org
acl ip_test src 172.168.217.1 192.168.0.0/24
########### host ###########################
http-request deny if web_host
########### default server ###################
default_backend default_webserver
backend ip_test-host
mode http
server web1 192.168.217.10:80 check weight 1 inter 3s fall 3 rise 5
backend default_webserver
mode http
server web1 172.217.168.10:80 check weight 1 inter 3s fall 3 rise 5
haproxy ~]# vim /etc/haproxy/haproxy.cfg
frontend testacl
bind :80
mode http
########### ACL settings #######################
acl user_agent_block hdr_sub(User-Agent) -i curl wget
acl user_agent_redirect hdr_sub(User-Agent) -i Mozilla/5.0
########### host ###########################
http-request deny if user_agent_block
redirect prefix https://www.baidu.com if user_agent_redirect
########### default server ###################
default_backend default_webserver
backend ip_test-host
mode http
server web1 192.168.217.10:80 check weight 1 inter 3s fall 3 rise 5
backend default_webserver
mode http
server web1 172.217.168.10:80 check weight 1 inter 3s fall 3 rise 5
1.
[root@client ~]# curl 192.168.217.100
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>
2.
[root@client ~]# wget http://192.168.217.100/index.html
--2025-07-22 16:04:36-- http://192.168.217.100/index.html
Connecting to 192.168.217.100:80... connected.
HTTP request sent, awaiting response... 403 Forbidden
--2025-07-22 16:04:36-- ERROR 403: Forbidden.
3.浏览器中测试
haproxy ~]# vim /etc/haproxy/haproxy.cfg
frontend testacl
bind :80
mode http
########### ACL settings #######################
acl url_static path_end -i .jpg .png .css .js .html
acl url_php path_end -i .php
########### host ###########################
use_backend static_host if url_static
use_backend php_host if url_php
########### default server ###################
default_backend default_webserver
backend ip_test-host
mode http
server web1 192.168.217.10:80 check weight 1 inter 3s fall 3 rise 5
backend default_webserver
mode http
server web1 172.217.168.10:80 check weight 1 inter 3s fall 3 rise 5
[root@rs1 ~]# echo css 192.168.217.10 > /usr/share/nginx/html/index.css
[root@rs2 ~]# echo php 192.168.217.20 > /var/www/html/index.php
[root@node10 ~]# curl 192.168.217.100/index.php
php 192.168.217.20
[root@node10 ~]# curl 192.168.217.100/index.css
css 192.168.217.10
haproxy ~]# vim /etc/haproxy/haproxy.cfg
frontend testacl
bind :80
mode http
########### ACL settings #######################
acl url_static path_end -i .jpg .png .css .js .html
acl url_static path_end -m sub /static /images /javascript
acl acl_app path_beg -m sub /api
########### host ###########################
use_backend static_host if url_static
use_backend api_host if acl_app
########### default server ###################
default_backend default_webserve
backend ip_test-host
mode http
server web1 192.168.217.10:80 check weight 1 inter 3s fall 3 rise 5
backend default_webserver
mode http
server web1 172.217.168.10:80 check weight 1 inter 3s fall 3 rise 5
#创建相关文件
[root@rs1 ~]# mkdir /usr/share/nginx/html/static
[root@rs1 ~]# echo static 192.168.217.10 > /usr/share/nginx/html/static/index.html
[root@rs2 ~]# mkdir /var/www/html/api/
[root@rs2 ~]# echo api 192.168.217.20 > /var/www/html/api/index.html
#测试访问
[root@node10 ~]# curl 192.168.217.100/api/
api 192.168.217.20
[root@node10 ~]# curl 192.168.217.100/static/
static 192.168.217.10