in apisix/plugins/proxy-rewrite.lua [271:393]
function _M.rewrite(conf, ctx)
for _, name in ipairs(upstream_names) do
if conf[name] then
ctx.var[upstream_vars[name]] = conf[name]
end
end
local upstream_uri = ctx.var.uri
local separator_escaped = false
if conf.use_real_request_uri_unsafe then
upstream_uri = ctx.var.real_request_uri
end
if conf.uri ~= nil then
separator_escaped = true
upstream_uri = core.utils.resolve_var(conf.uri, ctx.var, escape_separator)
elseif conf.regex_uri ~= nil then
if not str_find(upstream_uri, "?") then
separator_escaped = true
end
local error_msg
for i = 1, #conf.regex_uri, 2 do
local captures, err = re_match(upstream_uri, conf.regex_uri[i], "jo")
if err then
error_msg = "failed to match the uri " .. ctx.var.uri ..
" (" .. conf.regex_uri[i] .. ") " .. " : " .. err
break
end
if captures then
ctx.proxy_rewrite_regex_uri_captures = captures
local uri, _, err = re_sub(upstream_uri,
conf.regex_uri[i], conf.regex_uri[i + 1], "jo")
if uri then
upstream_uri = uri
else
error_msg = "failed to substitute the uri " .. ngx.var.uri ..
" (" .. conf.regex_uri[i] .. ") with " ..
conf.regex_uri[i + 1] .. " : " .. err
end
break
end
end
if error_msg ~= nil then
core.log.error(error_msg)
return 500, { error_msg = error_msg }
end
end
if not conf.use_real_request_uri_unsafe then
local index
if separator_escaped then
index = str_find(upstream_uri, "?")
end
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
req_set_uri(upstream_uri)
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
else
ctx.var.upstream_uri = upstream_uri
end
if conf.headers then
local hdr_op, err = core.lrucache.plugin_ctx(lrucache, ctx, nil,
create_header_operation, conf.headers)
if not hdr_op then
core.log.error("failed to create header operation: ", err)
return
end
local field_cnt = #hdr_op.add
for i = 1, field_cnt, 2 do
local val = core.utils.resolve_var_with_captures(hdr_op.add[i + 1],
ctx.proxy_rewrite_regex_uri_captures)
val = core.utils.resolve_var(val, ctx.var)
if val then
local header = hdr_op.add[i]
core.request.add_header(ctx, header, val)
end
end
local field_cnt = #hdr_op.set
for i = 1, field_cnt, 2 do
local val = core.utils.resolve_var_with_captures(hdr_op.set[i + 1],
ctx.proxy_rewrite_regex_uri_captures)
val = core.utils.resolve_var(val, ctx.var)
core.request.set_header(ctx, hdr_op.set[i], val)
end
local field_cnt = #hdr_op.remove
for i = 1, field_cnt do
core.request.set_header(ctx, hdr_op.remove[i], nil)
end
end
if conf.method then
ngx.req.set_method(switch_map[conf.method])
end
end