Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 2 down vote accepted


The key for the hash is the class-C network address of the client.

Also from:

     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) {
    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];
    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.

share|improve this answer

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.

    set_real_ip_from;  # 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
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.