Nginx Location Regex – How to Match Directory Range with Nginx Location Regex

nginxregex

I am trying to set up nginx and I don't get the point how to do the following setup:

I have an URL http://somehost.com/foo/bar/123/xxx_xxx that needs to be passed to different backends depending on a range the '123' matches (e.g. 0-150 -> backend1, 151-400 -> backend2, …).

Since I have almost no experience with regexp, I don't know how to do this (in location?).

Thanks in advance for your help,
Sascha

Best Answer

You can use:

location ~ ^/foo/bar/(\d|\d\d|1[0-4]\d|150)/ {
    proxy_pass backend1;
}

location ~ ^/foo/bar/(15[1-9]|1[6-9]\d|[23]\d\d|400)/ {
    proxy_pass backend2;
}
...

But why you do load balancing in such a heterogeneous way? Why not just shard by image id/hash of name? Your solution will result in different load and even load patterns on different servers. It would be tricky to administer them.