Welcome! Log In Create A New Profile


Proxying when a cookie is present

November 19, 2012 10:32PM
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;
# 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 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.

Jan Segre
Subject Author Posted

Proxying when a cookie is present

jansegre November 19, 2012 10:32PM

Sorry, only registered users may post in this forum.

Click here to login

Online Users

Guests: 86
Record Number of Users: 6 on February 13, 2018
Record Number of Guests: 214 on March 20, 2018
Powered by nginx      Powered by FreeBSD      PHP Powered      Powered by MariaDB      ipv6 ready