openresty 根据不同域名指向backend

需求

泛域名*.fk.cn,根据不同类型域名把api路由到不同的backend上,之前想法很简单,方案1.使用if判断把代码的指令放到判断体中 方案2.在pass_proxy 中使用变量但是后来发现变量在 pass_proxy中是不会被解析成backend地址的,现在使用的是方案3
这里写图片描述

伪代码

定义固定类型字典


init_by_lua '
-- 引入ngx.re模块 , 定义城市字典全局table变量
ngx_re = require "ngx.re"
test_city = {"hefei","wuhu","bengbu","fuyang","huainan"}
';

处理逻辑


location / {
rewrite_by_lua ’
local testhost = ngx.var.host
local res, err = ngx_re.split(testhost,”字符”)
local second_domain = res[1]

        function match_city(host)
                      for index in pairs(test_city) do
                             if test_city[index] == host then
                                    return true
                             end
                      end
                      return false
                end

        local match_result = match_city(second_domain)

        if match_result then
            ngx.exec("@k-location")
        else
            ngx.exec("@x-location")
        end
    ';
}
location @k-location {
    proxy_pass      http://localhost:81;
}

location @jx-location {
    proxy_pass      http://localhost:82;
}
</code>

这种方式唯一不好就是导致服务器的tcp连接会x1,产生的日志x1,如果不能接受这些的话可以把81,82放到别的服务器再做处理

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值