Proxying when a cookie is present

I’m trying to configure nginx to proxy_pass to a hot-test server when a
certain cookie is present.

It’s expected to work like this:

  • accessing /hot will set a cookie hot=1 and redirect to /
  • accessing /prod will set the cookie hot=0 and redirect to /
  • when there is this cookie hot=1 then the requests should be proxied to
    the
    test server
  • otherwise regular static and other proxies will take place

What I couldn’t do so far:

  • an if that has higher priority over a location so static files won’t
    try
    to be served before the proxy to the test takes place

I managed to make this work doing an internal proxy to isolate my
configurations on different server directives more a less like this:

server {
    listen 80;
    server_name myserver.com _;
    location = /hot {
        add_header Set-Cookie "hot=1;Max-Age=3600";
        rewrite ^ / redirect;
    }
    location = /prod {
        add_header Set-Cookie "hot=0;Max-Age=3600";
        rewrite ^ / redirect;
    }
    location ^~ /somepage/ {
        if ($http_cookie ~* "hot=1") {
            proxy_pass http://mytestserver.com;
            break;
        }
        # this is where the hacking begins
        proxy_set_header X-Real-Host $host;
        proxy_set_header Host somepage;
        proxy_pass http://localhost:666;
    }
}
server {
    listen 666;
    server_name somepage;
    allow 127.0.0.1;
    deny all;
    location ^~ /somepage/ {
        # here I can peacefully write what I needed before
        # but when I try to do so it seems to have priority over the if
directive
        location ~* /somepage/(.+)\.(css|js)$ {
            expires 1h;
            alias /path/to/files/$1.$2;
        }
        location ~*
/somepage/(.+)\.(jpg|jpeg|png|gif|bmp|ico|pdf|flv|swf|woff)$ {
            expires 7d;
            alias /path/to/files/$1.$2;
        }
        proxy_set_header Host $http_x_real_host;
        proxy_pass http://myjavaloadbalancer.com:8080;
    }
}

That’s basically it, there are other locations and details like
access_log,
but I think the above is the relevant part.
I’d really appretiate a better way to do this.

Posted at Nginx Forum:
http://forum.nginx.org/read.php?2,232993,232993#msg-232993

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs