Routing based on cookies

Kamil Gorlo kgs4242 at
Sun Aug 14 20:40:41 UTC 2011

Hi guys!

I have Nginx configured as load balancer to some number of application
servers. I need to configure Nginx in such a way that if there is
cookie set in request ("server_id=<some_number>"), I have to forward
this request to backend identified by <some_number> - if there is no
cookie set, every server could be chosen with equal probability to
serve request.

So my need is something similar to functionality given by nginx
upstream hash module. But I want to have more control of which server
has to be chosen. It has to be exact server pointed by variable (in
this case: cookie value) - no hash calculations.

Something like this:

upstream {
   server app-1;
   server app-2;
   server app-3;
   choose $cookie_SERVER_ID;

When cookie "SERVER_ID" is present in request and it is number from 1
to 3 (which means order in server listed in config or suffix in server
name), it should suggest that this particular request should be
forwarded to app-<NUM> server. But when there is no cookie, standard
round-robin algorithm could be used for balancing. Also when some
server is dead (even if it is chosen by variable from cookie) request
should be forwarded to next live backend.

How to do this? Is writing own module (similar to upstream hash) the
simplest idea? Or is there something more clever?

Best regards,

More information about the nginx mailing list