diff --git a/apisix/balancer.lua b/apisix/balancer.lua index fbcae258..fde2e58d 100644 --- a/apisix/balancer.lua +++ b/apisix/balancer.lua @@ -288,7 +288,6 @@ end function _M.run(route, ctx, plugin_funcs) local server, err - local header_changed if ctx.picked_server then -- use the server picked in the access phase @@ -311,6 +310,7 @@ function _M.run(route, ctx, plugin_funcs) return core.response.exit(502) end + local header_changed local pass_host = ctx.pass_host if pass_host == "node" and balancer.recreate_request then local host = server.domain or server.host @@ -321,12 +321,11 @@ function _M.run(route, ctx, plugin_funcs) end end - end - - local _, run = plugin_funcs("balancer") - -- always recreate request as the request may be changed by plugins - if (run or header_changed) and balancer.recreate_request then - balancer.recreate_request() + local _, run = plugin_funcs("balancer") + -- always recreate request as the request may be changed by plugins + if (run or header_changed) and balancer.recreate_request then + balancer.recreate_request() + end end core.log.info("proxy request to ", server.host, ":", server.port) diff --git a/apisix/init.lua b/apisix/init.lua index 481b4c66..6556151d 100644 --- a/apisix/init.lua +++ b/apisix/init.lua @@ -321,6 +321,23 @@ local function verify_tls_client(ctx) end +local function common_phase(phase_name) + local api_ctx = ngx.ctx.api_ctx + if not api_ctx then + return + end + + plugin.run_global_rules(api_ctx, api_ctx.global_rules, phase_name) + + if api_ctx.script_obj then + script.run(phase_name, api_ctx) + return api_ctx, true + end + + return plugin.run_plugin(phase_name, nil, api_ctx) +end + + function _M.http_access_phase() local ngx_ctx = ngx.ctx @@ -501,6 +518,9 @@ function _M.http_access_phase() set_upstream_headers(api_ctx, server) + -- run the balancer phase in access phase first to avoid always reinit request + common_phase("balancer") + local ref = ctxdump.stash_ngx_ctx() core.log.info("stash ngx ctx: ", ref) ngx_var.ctx_ref = ref @@ -546,23 +566,6 @@ function _M.grpc_access_phase() end -local function common_phase(phase_name) - local api_ctx = ngx.ctx.api_ctx - if not api_ctx then - return - end - - plugin.run_global_rules(api_ctx, api_ctx.global_rules, phase_name) - - if api_ctx.script_obj then - script.run(phase_name, api_ctx) - return api_ctx, true - end - - return plugin.run_plugin(phase_name, nil, api_ctx) -end - - local function set_resp_upstream_status(up_status) core.response.set_header("X-APISIX-Upstream-Status", up_status) core.log.info("X-APISIX-Upstream-Status: ", up_status) @@ -909,6 +912,9 @@ function _M.stream_preread_phase() end api_ctx.picked_server = server + + -- run the balancer phase in preread phase first to avoid always reinit request + common_phase("balancer") end