我需要兩組不同的上游。但我所有的請求都來自相同的 URL(相同的路徑)。不同之處在於,有些請求會有特殊參數,有些則沒有。根據這一點,我需要選擇要使用的上游。這是我的設定檔範例的不完整部分:
server_name localhost;
root /var/www/something/;
upstream pool1
{
server localhost:5001;
server localhost:5002;
server localhost:5003;
}
upstream pool2
{
server localhost:6001;
server localhost:6002;
server localhost:6003;
}
location /
{
# this is the part where I need help
try_files $uri @pool1;
}
location @pool1
{
include fastcgi_params;
fastcgi_pass pool1;
}
location @pool2
{
include fastcgi_params;
fastcgi_pass pool2;
}
所以...我不知道的部分是如何檢查參數/參數是否在 URL 中,並根據情況使用位置 pool1 或 pool2。
知道如何實現這個嗎?
謝謝!
答案1
@hellvinz 是對的。我無法發表評論,所以我正在做另一個答案。
location / {
if($myArg = "otherPool") {
rewrite ^/(.*)$ /otherUpstream/$1 last;
}
try_files $uri pool1;
}
location /otherUpstream {
proxy_pass http://@pool2;
}
我認為您必須將 $myArg 更改為您正在測試的查詢參數的名稱,並將 otherPool 更改為您設定的任何值。另外,重寫未經測試,所以我也可能有這個錯誤,但你明白了。
答案2
我想提出這個的替代版本沒有如果陳述。我知道這是一個較舊的問題,但未來的Google用戶可能仍然會發現這很有幫助。
我必須承認,這也意味著改變你選擇上游的方式。但我看不出這樣做有什麼問題。
這個想法是隨請求發送自訂 HTTP 標頭 (X-Server-Select)。這允許 nginx 選擇正確的池。如果標題不存在,則會選擇預設值。
你的配置可能會變成這樣:
upstream pool1
{
server localhost:5001;
server localhost:5002;
server localhost:5003;
}
upstream pool2
{
server localhost:6001;
server localhost:6002;
server localhost:6003;
}
# map to different upstream backends based on header
map $http_x_server_select $pool {
default "pool1";
pool1 "pool1";
pool2 "pool2";
}
location /
{
include fastcgi_params;
fastcgi_pass $pool;
}
來源:nginx 根據 http header 使用不同的後端
作為未來的我回到這裡後添加:要輕鬆測試伺服器,您可以在 chrome 中安裝擴充功能(我使用 ModHeader),允許您修改請求標頭。