使用haproxy的ACL实现基于文件后缀名的动静分离
实验架构
1.后端服务器安装httpd
1.修改主机名
1)
[root@centos7:~]#
hostnamectl set-hostname rs1.magedu.org;exit
2)
[root@centos7:~]#
hostnamectl set-hostname rs1.magedu.org;exit
2.安装httpd
1)
[root@rs1:~]#
yum -y install httpd;systemctl enable --now htppd
2)
[root@rs1:~]#
yum -y install httpd;systemctl enable --now htppd
2.后端服务器制作动态和静态文件
1)
[root@rs1:~]#
cd /var/www/html
[root@rs1:/var/www/html]#
echo `hostname -I` > m.txt
[root@rs1:/var/www/html]#
echo `hostname -I` > m.js
[root@rs1:/var/www/html]#
echo `hostname -I` > m.php
2)
[root@rs2:~]#
cd /var/www/html
[root@rs2:/var/www/html]#
echo `hostname -I` > m.txt
[root@rs2:/var/www/html]#
echo `hostname -I` > m.js
[root@rs2:/var/www/html]#
echo `hostname -I` > m.php
3.代理服务器端安装haproxy
1.修改主机名
[root@centos7:~]#
hostnamectl set-hostname haproxy.magedu.org;exit
2.安装haproxy,编译安装方法详见此连接
https://blog.csdn.net/aa896517050/article/details/125682165
3.创建子配置文件,在自配置文件中配置规则更方便
[root@haproxy:~]#
mkdir /etc/haproxy/conf.d/
4.添加子配置目录到unit文件中
[root@haproxy:~]#
vim /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
[Install]
WantedBy=multi-user.target
[root@centos7 ~]#systemctl daemon-reload
[root@centos7 ~]#systemctl restart haproxy
#总结
#1.先建好自配置文件夹
#2.修改service文件,利用-f 指向自配置文件夹
5.添加自配置文件规则
[root@haproxy:~]#
vim /etc/haproxy/conf.d/test.cfg
frontend m44_web_80
bind 10.0.0.100:80
acl acl_user_agent hdr_sub(User-Agent) -i curl wgeti
#acl acl_static path_beg -i /static /images /javascript #基于路径的ACL
acl acl_static path_end -i .jpg .jpeg .png .gif .css .js .html .htm #此项目为ACL同名为或关系
acl acl_app path_beg -i .php
use_backend static_hosts if acl_static
use_backend app_hosts if acl_php
default_backend app_hosts
backend static_hosts
server 10.0.0.18 10.0.0.18:80 check
backend app_hosts
server 10.0.0.28 10.0.0.28:80 check
4.客户端检测
[root@centos8:~]#
hostnamectl set-hostname client.magedu.org;exit
#m.txt文件不属于任何种类,按照deafult调度结果,调度到app_hosts(10.0.0.28)
[root@client:~]#
curl www.magedu.org/m.txt
10.0.0.28
[root@client:~]#
curl www.magedu.org/m.txt
10.0.0.28
#m.js属于指定的静态资源,调度到static_hosts(10.0.0.18)
[root@client:~]#
curl www.magedu.org/m.js
10.0.0.18
[root@client:~]#
curl www.magedu.org/m.js
10.0.0.18
#m.php属于指定的动态资源,调度到aap_hosts(10.0.0.28)
[root@client:~]#
curl www.magedu.org/m.php
10.0.0.28
[root@client:~]#
curl www.magedu.org/m.php
10.0.0.28