Proxying when a cookie is present

jansegre nginx-forum at
Tue Nov 20 03:32:37 UTC 2012

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 _;
    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") {
        # 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;
    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
        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;

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:,232993,232993#msg-232993

More information about the nginx mailing list