nginx routing based on ip address

digitalkapitaen nginx-forum at forum.nginx.org
Wed Feb 24 17:49:32 UTC 2016


keeyong Wrote:
-------------------------------------------------------
> I am wondering if it is possible to compute some kind of hash value
> from ip address or do modulo operation on the last numeric value from
> ip address (for example on 24 given 172.16.4.24)? Based on this, I
> want to send the request to different endpoints (not to different
> servers). If this can be done without installing any new module, that
> would be the best.
> 
> As far as I can see, I feel like I should do something similar using
> the regex?

Yes, regex and map should help. If you want to derive four distinct values,
you can do something like this:

  map $remote_addr $key {
    ~\.[0-9]$       1; # 0..9
    ~\.[0-5][0-9]$  1; # 10..59
    ~\.6[0-4]$      1; # 60..64
    ~\.6[5-9]$      2; # 65..69
    ~\.[7-9][0-9]$  2; # 70..99
    ~\.1[0-1][0-9]$ 2; # 100..119
    ~\.12[0-8]$     2; # 120..128
    ~\.129$         3; # 129
    ~\.1[3-8][0-9]$ 3; # 130..189
    ~\.19[0-2]$     3; # 190..192
    default        4;
  }

Caveats: This does not work for IPv6. 

I have no idea if the fourth IP byte is normally distributed. If not, then
may generate a full mapping (~\.1$, ~\.2$, ... ~\.10$, ..., ~\.99$, ..,
~\.255$)

If you want to do something even more fancy you can go totally binary with
the $binary_remote_addr variable and \xYY in the regexp (never tried this as
it is more difficult to debug).

Oliver

Posted at Nginx Forum: https://forum.nginx.org/read.php?2,264742,264786#msg-264786



More information about the nginx mailing list