前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >nginx动态proxy_pass

nginx动态proxy_pass

作者头像
心平气和
发布2020-11-11 12:45:52
3.9K0
发布2020-11-11 12:45:52
举报
文章被收录于专栏:程序员升级之路

有时我们想根据用户请求的参数转发到不同的upstream,像做多机房用户路由的时候是非常有用的,实现有多种方式,一是设置不同的loction,然后让lua动态执行不同的子请求;还有就是将upstream设置成变量,让lua根据参数动态计算出upstream。

下面演示第二种方式,假设我们的域名为aa.com,nginx配置如下:

代码语言:javascript
复制
upstream order0{
        server 127.0.0.1:12580;
}

upstream order1{
        server 127.0.0.1:11580;
}

server {
  listen 443 ssl;
  server_name aa.com;
 

  location / { 
    set_by_lua_file $ups /data/lua/upsteam.lua;
    
    add_header X-CLOSED 0;
    proxy_pass_header Server;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header Accept-Encoding ""; 
    proxy_set_header X-Scheme $scheme;
    client_max_body_size 200m;
    proxy_pass http://$ups;
  }
}

上面的配置设置了2个upsteam,通过set_by_lua_file指令设置变量ups,然后请求到ups变量指向的upstream中,lua代码如下:

代码语言:javascript
复制
--ip to hash函数
function iptolong(ip)
    local first_index = 1
    local last_index = 1
    local cur_index=1
    local arr = {}
    local res
    local split_str
  
    split_str = "%."
    while true do
       first_index,_  = string.find(ip, split_str, last_index)
       if nil == first_index then
        arr[cur_index] = string.sub(ip, last_index, string.len(ip))
        break
       end
       arr[cur_index] = string.sub(ip, last_index, first_index - 1)
       last_index = first_index + 1
       cur_index = cur_index + 1
    end
  
    res = tonumber(arr[1])*256*256*256;
    res = res + tonumber(arr[2])*65536;
    res =res + tonumber(arr[3])*256;
    res = res + tonumber(arr[4]);
    return res
end

local ip = ngx.var.remote_addr;
local ip_hash

ip_hash = iptolong(ip) % 2;

if ip_hash == 1 then
  return "order1"
else
  return "order0"
end

上面我们根据用户IP做一次路由,偶数的返回order0,反之返回order1,这样不同的IP返回不同的upstream了;然后可以在浏览器访问 aa.com的一个地址,可以让每个服务器返回不同的东西就可以看到效果了。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-11-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员升级之路 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档