Switching backends based on a cookie

Marcus Clyne ngx.eugaia at gmail.com
Fri Jan 29 05:50:12 MSK 2010

saltyflorida wrote:
> I forgot to mention that I am using caching with the HTTP Proxy module and that I only want to cache responses from the production servers. When I have the cookie set to "testing" or "staging", I'd like to bypass the cache and talk directly to the backend. Does this sound feasible?
Sure.  Do a rewrite using your $backend variable under the 'location /' 
block to one of three other blocks, which have the different definitions 
of your proxy_pass, proxy_cache_valid...


map $cookie_[name]  $backend {

    default   production;
    test      test;

location   / {
    rewrite   ^(.*)$   /$backend/$1;

location   /production/ {
    proxy_pass            http://backend_production;
    proxy_cache_valid   ...

location   /test/ {
    # no proxy_cache_valid

Note, you'll need some way to catch the case of no cookie variable, so 
it's unwise to put $cookie_[name] directly in the rewrite result (you'll 
get an infinite loop on such results).


More information about the nginx mailing list