Nginx基于user_agent及浏览器实现转发
【基于客户端设备】服务说明列表:
节点 IP及端口 测试地址 字符串为代表业务
web01 10.0.0.7:80 客户端(PC、谷歌浏览器) pc_pools
web02 10.0.0.8:80 iphone(谷歌f12模拟或者手机访问) phone_pools
使用相同的域名,根据来源设备调度到不同的服务器集群
web01:pc
[root@web01 ~]# cat /etc/nginx/conf.d/www.etiantian.org.conf
server {
listen 80;
server_name www.etiantian.org;
root /data/agent;
location / {
index index.html;
}
}
[root@web01 ~]# mkdir /data/agent/
[root@web01 ~]# echo "PC....web01" > /data/agent/index.html
web02:手机
[root@web02 ~]# cat /etc/nginx/conf.d/www.etiantian.org.conf
server {
listen 80;
server_name www.etiantian.org;
root /data/agent;
location / {
index index.html;
}
}
[root@web02 ~]# mkdir /data/agent -p
[root@web02 ~]# echo "Phone..web02" > /data/agent/index.html
[root@web02 ~]# nginx -t
[root@web02 ~]# systemctl reload nginx
负载均衡配置:
[root@lb01 conf.d]# cat 01_www.etiantian.org.conf
upstream pc {
server 172.16.1.7:80;
}
upstream iphone {
server 172.16.1.8:80;
}
server {
listen 80;
server_name www.etiantian.org;
location / {
proxy_set_header Host $Http_host;
# 判断如果来源是手机则调度到phone集群组
if ($http_user_agent ~* "iPhone|android|ipad" ) {
proxy_pass http://iphone;
}
if ($http_user_agent ~* "firefox|MSIE|Chrome|Trident") {
return 200 'Please Change Browser.....';
#return 302 'http://www.oldboyedu.com';
}
# 如果来源不是手机,则调度到pc集群组
proxy_pass http://pc;
}
}
模拟访问
提示:可以使用curl的-A功能模拟User_agent。谷歌f12模拟iphone。
[root@lb01 conf]# curl -A "android" http://www.etiantian.org/upload/
upload server
[root@lb01 conf]# curl -A "iphone" http://www.etiantian.org/static/
static server
[root@lb01 conf.d]# curl -A "iphone" -H "host:www.etiantian.org" 10.0.0.5
iphone or android
[root@lb01 conf.d]# curl -A "android" -H "host:www.etiantian.org" 10.0.0.5
iphone or android
[root@lb01 conf.d]# curl -H "host:www.etiantian.org" 10.0.0.5
pc电脑或谷歌浏览器
[root@lb01 conf.d]# curl -A "Chrome" -H "host:www.etiantian.org" 10.0.0.5
Please Change Browser.....
[root@lb01 conf.d]# curl -A "firefox" -H "host:www.etiantian.org" 10.0.0.5
Please Change Browser.....
[root@lb01 conf.d]# curl -A "MSIE" -H "host:www.etiantian.org" 10.0.0.5
Please Change Browser.....