What IP does nginx use for ip_hash sticky sessions?
Solution 1
From:
http://wiki.nginx.org/HttpUpstreamModule#ip_hash
The key for the hash is the class-C network address of the client.
Also from:
nginx-0.8.53/src/http/modules/ngx_http_upstream_ip_hash_module.c:
91 static ngx_int_t
92 ngx_http_upstream_init_ip_hash_peer(ngx_http_request_t *r,
93 ngx_http_upstream_srv_conf_t *us)
94 {
...
114 if (r->connection->sockaddr->sa_family == AF_INET) {
115
116 sin = (struct sockaddr_in *) r->connection->sockaddr;
117 p = (u_char *) &sin->sin_addr.s_addr;
118 iphp->addr[0] = p[0];
119 iphp->addr[1] = p[1];
120 iphp->addr[2] = p[2];
121
122 } else {
123 iphp->addr[0] = 0;
124 iphp->addr[1] = 0;
125 iphp->addr[2] = 0;
126 }
...
164 for (i = 0; i < 3; i++) {
165 hash = (hash * 113 + iphp->addr[i]) % 6271;
166 }
Validating the documentation. It would be pretty easy to modify the code to include data like the XFF.
Solution 2
While this question is quite old and the answer is correct, after some digging to resolve my own load balancing problem I found that there is a newer option to make the client ip based on the X-Forwarded-For or X-Real-IP and when combined with the ip_hash directive it properly balances load using the user's actual IP as the hash.
http://nginx.org/en/docs/http/ngx_http_realip_module.html
set_real_ip_from 127.0.0.1; # nginx and varnish on other ports
real_ip_header X-Real-IP; # or X-Forwarded-For
# real_ip_recursive on; # doesn't work on nginx 1.0
Related videos on Youtube
Richard Nichols
Updated on September 18, 2022Comments
-
Richard Nichols over 1 year
Does nginx use the direct client's IP for ip_hash, or does it also observe X-forwarded-for HTTP header to use as the IP address to ip_hash?
For example, in a situation where some clients using a shared proxy server access an nginx load-balancer w/ ip_hash, would all of those clients hash to the same node?
Or would nginx use the X-forwarded-for header to hash them to different nodes?