Nginx Proxy redirect to clients when upstreams are busy

Maxim Dounin mdounin at mdounin.ru
Fri Dec 11 13:36:45 UTC 2015


Hello!

On Fri, Dec 11, 2015 at 11:52:23AM +0000, Prasanna Khanapur wrote:

> Hi,
> 
> I have built a custom load balancer "my_loadbalancer" which load balances
> request from end users.
> 
> -Ignore any syntax errors, if any-
> 
> upstream myservers {
>   my_loadbalancer;
>   server abc123;
>   server  pqr123;
> }
> 
> location XYZ {
>       proxy_pass http://myservers <http://abcdservers> ;
> }
> 
> I have basically followed Emiller's Guide to get all this working.
> "my_loadbalancer" loadbalances upstreams based on some conditions. Right
> now, loadbalancer's  "get_peer" function returns
> (1) NGX_OK  when it successfully finds upstream
> (2) NGX_BUSY when it fails to find upstream.
> 
> 
> In above case (1) works fine and client gets response and case (2)  works
> fine, loadbalancer sends the client a 502 Bad Gateway.
> 
> Now I want to do something more where I need help.
> In case (2),  instead of sending a 502, I would like loadbalancer to send a
> redirect (either 301 or 302, not decided yet) so that client gets a
> redirect and connects to completely different Loadbalancer.
> 
> I'm looking at ngx_http_upstream_connect() in ngx_http_upstream.c where
> return from loadbalancer is handled. I dont see a simple way to make it
> generate redirect  response.
> 
> 
> I want to do this programtically because the different loadbalancer
> instance which I want the client should connect to(indicated through
> redirect) is decided on the fly.
> 
> 
> Anyone has any inputs/suggestions ? Thanks!

This is something you can easily do with configuration, using the 
error_page directive (http://nginx.org/r/error_page), like this:

    error_page 502 = @fallback;

    location @fallback {
        return 302 $some_other_uri;
    }

If you want to provide URI to redirect to from your module, you 
can export it using a variable ($some_other_uri in the example).

-- 
Maxim Dounin
http://nginx.org/



More information about the nginx-devel mailing list