使用 nginx 负载平衡动态 php 站点

Load balancing dynamic php site using nginx

我有三台服务器。一个用于负载平衡,另外两个用于服务 Web 应用程序。如果我将我的网页用作静态站点,我的负载平衡工作正常。但是当我登录到我的网页时,它没有正确响应,因为每次它在页面加载时都会更改其服务器。我如何在注销前不更改当前服务器的情况下执行此操作。我的负载平衡服务器配置是

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;
    }
}

您可以使用 nginx 的 Session persistence 功能:

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:

在你的情况下,只需将 ip_hash 添加到你的上游定义中

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