openresty 根据不同域名指向backend,openrestybackend


需求

泛域名*.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放到别的服务器再做处理

相关内容

    暂无相关文章