nginx负载均衡之基于不同客户端

  • 负载均衡还可以根据不同客户端进行相应的转发

以下示例为基于不同手机端及浏览器进行转发

实验环境

角色 IP地址 主机名
负载均衡 lb 10.0.0.10 lb
真实后端服务 web01 10.0.0.51 web01
真实后端服务 web02 10.0.0.52 web02

让手机端的访问转发到web01,让浏览器的访问和默认访问转发到web02

负载均衡操作

upstream iphone {
  server 10.0.0.51;
}

upstream android {
  server 10.0.0.51:8080;
}

upstream chrom {
  server 10.0.0.52;
}

upstream firefox {
  server 10.0.0.52:8080;
}

upstream defaults {
  server 10.0.0.52;
}


server {
  listen 80;
  server_name _;
  location / {
    #匹配iPhone手机访问
    if ($http_user_agent ~* "iphone") {
      proxy_pass http://iphone;
    }

    #匹配Android手机访问
    if ($http_user_agent ~* "android") {
      proxy_pass http://android;
    }

    #匹配谷歌浏览器访问
    if ($http_user_agent ~* "chrom") {
      proxy_pass http://chrom;
    }

    #匹配firefox浏览器访问
    if ($http_user_agent ~* "firefox") {
      proxy_pass http://Firefox;
    }

    #其他浏览器访问默认规则
    proxy_pass http://defaults;
  }
}

web01操作

编辑nginx配置文件

server {
    listen 80;
    server_name _;
    root /data/iphone;
    index index.html;
}

server {
    listen 8080;
    server_name _;
    root /data/android;
    index index.html;
}

创建网站根目录

mkdir -p /data/{iphone,android}
echo 'iphone' >/data/iphone/index.html
echo 'android' >/data/android/index.html

web02操作

编辑nginx配置文件

server {
    listen 80;
    server_name _;
    root /data/chrom;
    index index.html;
}

server {
    listen 8080;
    server_name _;
    root /data/firefox;
    index index.html;
}

创建网站根目录

mkdir -p /data/{chrom,firefox}
echo 'chrom' >/data/chrom/index.html
echo 'firefox' >/data/firefox/index.html

浏览器访问验证

模拟iphone

iShot2020-06-2019.23.49

nginx访问日志

10.0.0.2 - - [20/Jun/2020:19:22:50 +0800] "GET / HTTP/1.1" 200 7 "-" "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1" "-"

模拟安卓手机

iShot2020-06-2019.25.52

nginx访问日志

10.0.0.2 - - [20/Jun/2020:19:21:29 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Mobile Safari/537.36" "-"

谷歌浏览器访问

iShot2020-06-2019.19.51

nginx访问日志

10.0.0.2 - - [20/Jun/2020:19:26:17 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36" "-"

火狐浏览器访问

iShot2020-06-2019.18.26

nginx访问日志

10.0.0.2 - - [20/Jun/2020:19:22:05 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:77.0) Gecko/20100101 Firefox/77.0" "-"
泡泡吐肥皂o © gitbook.pptfz.top 2021 all right reserved,powered by Gitbook文件修订时间: 秃笔南波湾!!!

results matching ""

    No results matching ""