ip_hash

The `ip_hash` directive enables session persistence by routing requests from the same client IP address to the same server in the upstream group.

Syntaxip_hash;
Defaultnone
Contextupstream
Argumentsnone

Description

The ip_hash directive is used in the context of an upstream block in NGINX configuration to provide consistent load balancing based on client IP addresses. By enabling ip_hash, NGINX hashes the client's IP address to determine which server within the upstream group should handle the request. This means that a user with the same IP will always be directed to the same backend server for each session, maintaining stateful sessions without requiring sticky sessions via cookies.

Request routing occurs by applying a hash function to the client's IP address, which ensures that IPs resolve to the same server consistently. If the request originates from a different client (by IP), it will be routed to possibly another server within the upstream set. This feature is particularly useful in maintaining session consistency for applications that do not inherently manage sessions and are sensitive to server selection. It should be noted that in environments where clients are behind proxies or load balancers, proper configuration of real_ip or handling will be necessary to ensure the correct client IP is used for hashing.

Config Example

upstream backend {
    ip_hash;
    server backend1.example.com;
    server backend2.example.com;
    server backend3.example.com;
}

Ensure that the upstream servers are capable of handling sessions independently as ip_hash does not share state across servers.

Using ip_hash can lead to uneven load distribution among servers, particularly in cases where some IPs send more traffic than others.

← Back to all directives