Is it possible to define a custom routing in NGINX or other Load Balancer? I.e. I have a cookie or a header and based on its value I decide which backend server to choose? I need some very simple logic - values a1,a2,a3 - to server A, values b1,b2 to server B, all other to server C
Asked
Active
Viewed 2,463 times
2 Answers
7
In nginx you can do it simply by using if:
location / {
if ($http_cookie ~* "yourcookiename=a") {
proxy_pass http://upstream_a;
break;
}
if ($http_cookie ~* "yourcookiename=b") {
proxy_pass http://upstream_b;
break;
}
proxy_pass http://upstream_c;
}
This is simple regexp , so this way if "yourcookiename" has value a1,a2 etc. it will go to uprstream_a and so on. Hope it helps...

Eryk
- 71
- 3
4
If you need some sticky session, there are open source third party modules that can do that with nginx, while the native implementation is part of the commercial subscription. Also, tengine, an open source chinese fork of nginx developed by Alibaba can do that natively.
If you want to do it the custom way, use a map to avoid processing a chain of if blocks for all requests. This is also better for readability. For instance, using a cookie :
map $cookie_mycookie $node {
"~^a[1-3]$" "A";
"~^b[1-2]$" "B";
default "C";
}
server {
location / {
proxy_pass http://$node;
}
}

Xavier Lucas
- 2,552
- 20
- 19
-
I do not need sticky session. Client side will set a cookie (say customer id) and I want redirect any customer to a specific server! – Pavel Bernshtam Nov 04 '14 at 18:28
-
1@PavelBernshtam Did you actually read my answer ?! I'm speaking about sticky sessions in the two first sentences, I guess you stopped reading after that. – Xavier Lucas Nov 04 '14 at 19:29