@@ -72,6 +72,8 @@ local function get_implementation(backend)
7272 return implementation
7373end
7474
75+ -- used to get the IP address of the upstream to set as the
76+ -- backends endpoint to route to
7577local function resolve_external_names (original_backend )
7678 local backend = util .deepcopy (original_backend )
7779 local endpoints = {}
@@ -181,6 +183,7 @@ local function sync_backends()
181183 backends_last_synced_at = raw_backends_last_synced_at
182184end
183185
186+ -- logic used to pick up if request should be routed to an alternative backend
184187local function route_to_alternative_balancer (balancer )
185188 if balancer .is_affinitized (balancer ) then
186189 -- If request is already affinitized to a primary balancer, keep the primary balancer.
@@ -218,7 +221,6 @@ local function route_to_alternative_balancer(balancer)
218221 " of backend: " , tostring (backend_name ))
219222 return false
220223 end
221-
222224 local target_header = util .replace_special_char (traffic_shaping_policy .header ,
223225 " -" , " _" )
224226 local header = ngx .var [" http_" .. target_header ]
@@ -278,14 +280,15 @@ local function get_balancer()
278280 local backend_name = ngx .var .proxy_upstream_name
279281
280282 local balancer = balancers [backend_name ]
283+
281284 if not balancer then
282285 return nil
283286 end
284287
285- if route_to_alternative_balancer (balancer ) then
288+ -- we should not overwrite balancer when it is the default backend
289+ if route_to_alternative_balancer (balancer ) and not balancer .is_default_backend then
286290 local alternative_backend_name = balancer .alternative_backends [1 ]
287291 ngx .var .proxy_alternative_upstream_name = alternative_backend_name
288-
289292 balancer = balancers [alternative_backend_name ]
290293 end
291294
318321
319322function _M .rewrite ()
320323 local balancer = get_balancer ()
324+
321325 if not balancer then
322326 ngx .status = ngx .HTTP_SERVICE_UNAVAILABLE
323327 return ngx .exit (ngx .status )
@@ -344,6 +348,7 @@ function _M.balance()
344348 ngx_balancer .set_more_tries (1 )
345349
346350 local ok , err = ngx_balancer .set_current_peer (peer )
351+
347352 if not ok then
348353 ngx .log (ngx .ERR , " error while setting current upstream peer " , peer ,
349354 " : " , err )
@@ -363,6 +368,16 @@ function _M.log()
363368 balancer :after_balance ()
364369end
365370
371+ -- this is used to check if we are routing to the
372+ -- default backend for sepcific error codes so that we do not overwrite it with
373+ -- alternative routes
374+ -- https://github.com/kubernetes/ingress-nginx/issues/9944
375+ function _M .is_default_backend ()
376+ if ngx .ctx .balancer then
377+ ngx .ctx .balancer .is_default_backend = true
378+ end
379+ end
380+
366381setmetatable (_M , {__index = {
367382 get_implementation = get_implementation ,
368383 sync_backend = sync_backend ,
0 commit comments