0
0
Nginxdevops~5 mins

IP hash for session persistence in Nginx - Commands & Configuration

Choose your learning style9 modes available
Introduction
When you have multiple servers handling user requests, you want each user to keep talking to the same server during their visit. IP hash helps by sending requests from the same user IP to the same server, so their session stays consistent.
When you run a website with multiple backend servers and want users to keep their session on one server.
When you have a shopping cart that must stay on the same server during checkout.
When you want to avoid losing user data by switching servers mid-session.
When you want a simple way to balance load but keep user sessions sticky.
When you cannot use cookies or other session tracking methods.
Config File - nginx.conf
nginx.conf
http {
    upstream myapp {
        ip_hash;
        server 192.168.1.101;
        server 192.168.1.102;
        server 192.168.1.103;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://myapp;
        }
    }
}

This configuration defines an upstream group named myapp with three backend servers.

The ip_hash; directive ensures requests from the same client IP go to the same server.

The server block listens on port 80 and forwards requests to the myapp upstream group.

Commands
Check the nginx configuration file syntax to make sure there are no errors before restarting.
Terminal
nginx -t
Expected OutputExpected
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
Restart the nginx service to apply the new configuration with IP hash load balancing.
Terminal
systemctl restart nginx
Expected OutputExpected
No output (command runs silently)
Send a simple HTTP request to verify nginx is responding and proxying requests.
Terminal
curl -I http://localhost
Expected OutputExpected
HTTP/1.1 200 OK Server: nginx Date: Wed, 01 Jan 2025 12:00:00 GMT Content-Type: text/html Content-Length: 612 Connection: keep-alive
Key Concept

If you remember nothing else from this pattern, remember: ip_hash sends requests from the same client IP to the same backend server to keep sessions sticky.

Common Mistakes
Not including the ip_hash directive inside the upstream block.
Without ip_hash, nginx will load balance without session persistence, causing user sessions to break.
Always add ip_hash; inside the upstream block to enable session persistence by client IP.
Forgetting to test nginx configuration before restarting.
A syntax error can cause nginx to fail restarting, making the site unavailable.
Run nginx -t to verify configuration syntax before restarting the service.
Summary
Define an upstream group with backend servers and add ip_hash; to enable session persistence by client IP.
Test nginx configuration syntax with nginx -t before restarting.
Restart nginx to apply the new configuration and verify with a simple HTTP request.