Switching backends based on a cookie

merlin corey merlincorey at dc949.org
Fri Jan 29 03:24:29 MSK 2010


On Thu, Jan 28, 2010 at 4:03 PM, Marcus Clyne <ngx.eugaia at gmail.com> wrote:
> Hi,
>
> saltyflorida wrote:
>>
>> Is it possible to switch backend clusters of servers based on a cookie?
>>
>> I would like to set a cookie named "env" and do something like this:
>>
>>        if ($http_cookie ~* "env=testing(;|$)") {
>>            proxy_pass http://backend_testing;
>>        }
>>        if ($http_cookie ~* "env=staging(;|$)") {
>>            proxy_pass http://backend_staging;
>>        }
>>        if ($http_cookie ~* "env=production(;|$)") {
>>            proxy_pass http://backend_production;
>>        }
>>
>> However the "proxy_pass" directive is not allowed inside an "if". Is there
>> another way I can approach this?
>>
>>
>
> Take a look at the map module :
>
> http://wiki.nginx.org/NginxHttpMapModule
>
> One possibility would be :
>
> http {
>
> map  $cookie_env  $backend {
>
>   testing      http://backend_testing;
>   staging      http://backend_staging;
>   production   http://backend_production;
> }
>
> server {
>   ...
>   proxy_pass   $backend;
>
> }
>
> }
>
> Marcus.
>
>
> _______________________________________________
> nginx mailing list
> nginx at nginx.org
> http://nginx.org/mailman/listinfo/nginx
>

Marcus' solution should be just fine, but I feel I must ask an
important question:

Doesn't it make more sense to have production, static, and dev as
separate server blocks entirely with their own hostnames?  This is, at
the least, traditional :).

-- Merlin



More information about the nginx mailing list