APISIX源码解析-插件-代理重写-【proxy-rewrite】

proxy-rewrite 代理重写

关键属性

在这里插入图片描述

源码实现

do
    local upstream_vars = {
        host       = "upstream_host",
        upgrade    = "upstream_upgrade",
        connection = "upstream_connection",
    }
    local upstream_names = {}
    for name, _ in pairs(upstream_vars) do
        core.table.insert(upstream_names, name)
    end

function _M.rewrite(conf, ctx)
    for _, name in ipairs(upstream_names) do
        if conf[name] then
            -- 设置var变量
            ctx.var[upstream_vars[name]] = conf[name]
        end
    end
    if conf["scheme"] then
        -- 设置上下文变量 schema: http / https
        ctx.upstream_scheme = conf["scheme"]
    end

    local upstream_uri = ctx.var.uri
    if conf.uri ~= nil then
        -- 对uri进行变量替换,可以是自定义也可以是ngx内置变量$
        upstream_uri = core.utils.resolve_var(conf.uri, ctx.var)
    elseif conf.regex_uri ~= nil then
        -- 正则匹配
        local uri, _, err = re_sub(ctx.var.uri, conf.regex_uri[1],
                                   conf.regex_uri[2], "jo")
        if uri then
            upstream_uri = uri
        else
            local msg = "failed to substitute the uri " .. ctx.var.uri ..
                        " (" .. conf.regex_uri[1] .. ") with " ..
                        conf.regex_uri[2] .. " : " .. err
            core.log.error(msg)
            return 500, {message = msg}
        end
    end

    local index = str_find(upstream_uri, "?")
    -- URL encode
    if index then
        upstream_uri = core.utils.uri_safe_encode(sub_str(upstream_uri, 1, index-1)) ..
                       sub_str(upstream_uri, index)
    else
        upstream_uri = core.utils.uri_safe_encode(upstream_uri)
    end
    
    -- 拼接query参数
    if ctx.var.is_args == "?" then
        if index then
            ctx.var.upstream_uri = upstream_uri .. "&" .. (ctx.var.args or "")
        else
            ctx.var.upstream_uri = upstream_uri .. "?" .. (ctx.var.args or "")
        end
    else
        ctx.var.upstream_uri = upstream_uri
    end

    if not conf.headers then
        return
    end

    -- reform header from object into array, so can avoid use pairs,
    -- which is NYI
    -- 设置转发上游的请求头
    if not conf.headers_arr then
        conf.headers_arr = {}

        for field, value in pairs(conf.headers) do
            core.table.insert_tail(conf.headers_arr, field, value)
        end
    end

    local field_cnt = #conf.headers_arr
    for i = 1, field_cnt, 2 do
        ngx.req.set_header(conf.headers_arr[i],
                           core.utils.resolve_var(conf.headers_arr[i+1], ctx.var))
    end
end

end  -- do
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值