nginx - 将 5% 的流量定向到 Web 服务器,其余只需 return 200

nginx - direct 5% of traffic to web server, simply return 200 for the rest

Nginx 大神们,求求你了

试图弄清楚我是否可以在 nginx 中使用权重来 "throttle" 特定 Web 服务器的流量。我希望 nginx 将 5% 的流量传递给 Web 服务器 (proxy_pass),其余的只是 return 状态代码 200。因此,它并不是真正的节流,因为我没有尝试 return 429 或任何东西,只是希望 nginx "throw out",在某种意义上,某个位置的 95% 的流量。客户端无所谓,只要拿回200就可以了。

我知道如何定义多个上游服务器之间的权重,但这不是一回事。可能吗?需要插件吗?

谢谢。

您可以尝试使用 split_clients 模块。它是一个原生的 Nginx 模块,可以在大多数 Nginx 发行版上使用。这是一个如何使用它的例子:

# Use this (and comment out the block below) if you want to
# send ~5% of the users to the upstream server, providing that the users
# have different IP addresses
split_clients "${remote_addr}" $not_a_winner {
    5%      ""; # winners
    *       "no_not_a_winner";
}

# Use this (and comment out the block above) if you want to
# send ~5% of all requests to the upstream server, and it doesn't
# matter if these requests come from the same or different users
split_clients "${connection}${connection_requests}${date_local}" $not_a_winner {
    5%      ""; # winners
    *       "no_not_a_winner";
}

server {
    ...

    location ... {
        # Setting the default_type makes it easier to test 
        # the configuration in a browser.
        default_type text/html; # You can omit this line

        if ($not_a_winner) {
            return 200;
        }

        ...
        proxy_pass ...
        ...
    }
}

我认为您可以按照在 nginx 配置中创建另一个服务器块来处理发送盲 200 的方式做一些事情。

upstream yourupstream {
    server localhost:82 weight=95;
    server yourbackend.com:80 weight=5;
}

server {
    listen 81;

    location / {
        return 200;
    }
}

server {
    listen 80;
    location /whatever {
        proxy_pass http://yourupstream;
    }
}