Controlling Nginx proxy target using a cookie?
Similar to this answer. Nginx's idiomatic approach to this kind of problems is via map
.
Basically, you define a map
in http
section
map $cookie_proxy_override $my_upstream {
default default-server-or-upstream;
~^(?P<name>[\w-]+) $name;
}
Then you simply use $my_upstream
in location
section(s):
location /original-request {
proxy_pass http://$my_upstream$uri;
}
Nginx evaluates map variables lazily, only once (per request) and when you are using them.
Eventually my solution boils down to this:
server {
...
set $upstream "default-server-or-upstream";
if ($http_cookie ~ "proxy_override=([\w-]+)") {
set $upstream $1;
}
location /original-request {
proxy_pass http://$upstream/original-application
}
}
The test is done in the server
scope for each request (before the actual redirect is resolved) and is just used to set a variable - this is apparently a supported usage of Nginx "rewrite" module. It also tests the entire $http_cookie
like @Rikih suggested, but includes the name of the cookie to make sure I don't match random stuff that people might be throwing at me.
Then in the location
scope where I want to do the redirect, I use the variable name that either contains the default upstream configuration or was overwritten by the cookie.
have you try $http_cookie ? http://wiki.nginx.org/HttpRewriteModule
if ($http_cookie ~* "proxy-target-A" ) { foo; }