web服务器资源分类场景实践
Nginx资源分离场景实践
系统版本 | 主机角色 | 外网IP | 内网IP | 提供端口 |
---|---|---|---|---|
CentOS7.5 | 负载均衡 | 10.0.0.5 | 172.16.1.5 | 80 |
CentOS7.5 | 提供Android页面 | 10.0.0.7 | 172.16.1.7 | 9090 |
CentOS7.5 | 提供Iphone页面 | 10.0.0.7 | 172.16.1.7 | 9091 |
CentOS7.5 | 提供pc页面 | 10.0.0.7 | 172.16.1.7 | 9092 |
1.配置后端WEB节点的Nginx配置
[root@web01 conf.d]# vim sj.conf
server {
listen 9090;
location / {
root /code/android;
index index.html;
}
}
server {
listen 9091;
location / {
root /code/iphone;
index index.html;
}
}
server {
listen 9092;
location / {
root /code/pc;
index index.html;
}
}
#浏览器使用IP+端口,访问到一个主机的不同的server,不同的location
server {
listen 80;
server_name m.android.com
root /code/android;
index index.html;
}
server {
listen 80;
server_name m.iphone.com
root /code/iphone;
index index.html;
}
server {
listen 80;
server_name m.pc.com
root /code/pc;
index index.html;
}
#浏览器通过不同的域名访问一个web的不同server,可以使用rewrite或return重定向URL
2.为后端WEB节点配置对应的网站目录及代码
[root@web01 conf.d]# mkdir /code/{android,iphone,pc}
[root@web01 conf.d]# echo "我是安卓" > /code/android/index.html
[root@web01 conf.d]# echo "我是iphone" > /code/iphone/index.html
[root@web01 conf.d]# echo "我是computer" > /code/pc/index.html
3.配置负载均衡服务,根据不同的浏览器调度到不同的资源地
~* 模糊匹配
$http_referer #记录是从哪个链接访问过来的,可以使用if判断referer
[root@lb01 conf.d]# vim /etc/nginx/conf.d/proxy_sj.conf
upstream android {
server 172.16.1.7:9090;
}
upstream iphone {
server 172.16.1.7:9091;
}
upstream pc {
server 172.16.1.7:9092;
}
server {
listen 80;
server_name cs.qy.com;
charset 'utf-8';
location / {
#如果客户端来源是Android则跳转到Android的资源;
if ($http_user_agent ~* "Android") {
proxy_pass http://android;
}
#如果客户端来源是Iphone则跳转到Iphone的资源;
if ($http_user_agent ~* "Iphone") {
proxy_pass http://iphone;
}
#如果客户端是IE浏览器则返回403错误;
if ($http_user_agent ~* "MSIE|Windows\ NT") {
return 403;
}
#默认跳转pc资源;
proxy_pass http://pc;
}
}
#没有判断的请求都访问到pc,相当于有个默认的else
#这个判断和location的判断类似
#rewrite可以做域名的强制跳转
4.使用浏览器访问,查看结果
PC端访问
浏览器模拟IPhone
[
浏览器模拟Android
[
实际线上的配置
server {
listen 80;
server_name www.drz.com;
if ($http_user_agent ~* "Android|Iphone") {
rewrite ^/$ https://m.ai.com redirect;
}
}