Nginx – IP Used for ip_hash Sticky Sessions

load balancingnginxPROXYsticky-sessions

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?

Best Answer

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.