Routing based on cookies

Kamil Gorlo kgorlo at gmail.com
Mon Aug 15 10:00:36 UTC 2011


2011/8/15 Jérôme Loyet <jerome at loyet.net>:
> 2011/8/14 Kamil Gorlo <kgs4242 at gmail.com>:
>> Hi guys!
>
> Hi
>
>>
>> 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?
>
> nginx sticky module (http://code.google.com/p/nginx-sticky-module/)
> does exactly what you're looking for.

Thanks! It looks great :)

> ++ Jerome

Kamil



More information about the nginx mailing list