使用haproxy的ACL实现基于文件后缀名的动静分离

发布时间 2023-10-07 15:24:16作者: 小糊涂90

 

#使用子配置文件
[root@localhost ~]# mkdir /etc/haproxy/conf.d/
#修改service文件
[root@localhost ~]# vim /usr/lib/systemd/system/haproxy.service
[Unit]
Description=HAProxy Load Balancer
After=syslog.target network.target
[Service]
ExecStartPre=/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -f /etc/haproxy/conf.d -c -q
ExecStart=/usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -f /etc/haproxy/conf.d -p /var/lib/haproxy/haproxy.pid
ExecReload=/bin/kill -USR2 $MAINPID
LimitNOFILE=100000
[Install]
WantedBy=multi-user.target


[root@localhost ~]# cat /etc/haproxy/conf.d/tets.cfg
frontend magedu_http_port
bind 10.0.0.152:80
mode http
balance roundrobin
log global
option httplog
###################### acl setting ###############################
acl acl_static path_end -i .jpg .jpeg .png .gif .css .js .html
acl acl_php path_end -i .php
###################### acl hosts #################################
use_backend mobile_hosts if acl_static
use_backend app_hosts if acl_php
default_backend pc_hosts
###################### backend hosts #############################
backend mobile_hosts
mode http
server web1 10.0.0.150 check inter 2000 fall 3 rise 5
backend pc_hosts
mode http
server web2 10.0.0.160:80 check inter 2000 fall 3 rise 5
backend app_hosts
mode http
server web2 10.0.0.160:80 check inter 2000 fall 3 rise 5



[root@localhost ~]# systemctl daemon-reload
[root@localhost ~]# systemctl restart haproxy

#分别在后端两台主机准备相关文件
#在10.0.0.150上
[root@centos8 ~]#ls /var/www/html/
index.html timg.jpg
#在10.0.0.160上
[root@centos8 ~]#cat /var/www/html/test.php
<?php
echo "<h1>http://10.0.0.160/test.php</h1>\n";
?>
#最后网页访问http://10.0.0.152/timg.jpg和http://10.0.0.152/test.php