Search code examples
phpnginxload-balancingsticky-session

Load balancing dynamic php site using nginx


I have three servers. One for load balancing other two for serving web application. My load balancing works fine if i use my web page as static site. but when i log into my web page it does not respond correctly because every time it changes its server when the page loads. how can i do it without changing current server before log-out. My load balancing server configuration is

upstream web_backend{
    server 192.168.33.2;
    server 192.168.33.3;
}

server{
    listen 80;

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://web_backend;
    }
}

Solution

  • You can use Session persistence feature of nginx:

    If there is the need to tie a client to a particular application server — in other words, make the client’s session “sticky” or “persistent” in terms of always trying to select a particular server — the ip-hash load balancing mechanism can be used.

    With ip-hash, the client’s IP address is used as a hashing key to determine what server in a server group should be selected for the client’s requests. This method ensures that the requests from the same client will always be directed to the same server except when this server is unavailable.

    To configure ip-hash load balancing, just add the ip_hash directive to the server (upstream) group configuration:

    In your case just add ip_hash into your upstream definition

    upstream web_backend{
        ip_hash;
        server 192.168.33.2;
        server 192.168.33.3;
    }