基於cookie在proxy_pass和uwsgi_pass之間切換?

基於cookie在proxy_pass和uwsgi_pass之間切換?

我的 nginx 伺服器目前設定為透過以下方式服務所有請求uwsgi_pass

location / {
  uwsgi_pass unix:///tmp/uwsgi-zerocater.sock;
  include uwsgi_params;
  uwsgi_read_timeout 7200;
  client_max_body_size 20M;
}

在我的應用程式程式碼中,我設定了一個名為 的 cookie,new_fe其值為「True」或「False」。

當值為“True”時,我想改為proxy_pass另一個外部伺服器,但僅限於特定路由。像下面這樣的東西虛擬程式碼

location ~ "^/my/complicated/regex$" {
  if ($cookie_new_fe = "True") {
    # pass the request to my other server
    # at something like http://other.server.com
  } else {
    # do the usual uwsgi stuff
  }
}

我怎樣才能做到這一點?我對 仍然有點陌生nginx,所以如果我缺少一些簡單的東西,請原諒這個問題。

答案1

作為臨時解決方案,這應該有效:

location ~ "^/my/complicated/regex$" {
  if ($cookie_new_fe = "True") {
    error_page 418 = @proxy;
    return 418;
  }

  # do the usual uwsgi stuff
}

location @proxy {
    # do proxy stuff
}

答案2

我進一步研究了地圖,並提出了這個解決方案,似乎有效(同時使用了@womble 和@alexey-ten 的建議):

map $cookie_new_fe $serve_request_from {
  default @uwsgi;
  "True" @proxy;
}

server {

  # ...

  # BEGIN Routes to switch based on value of $cookie_new_fe
  location ~ "^/my/complicated/regex$" {
    error_page 418 = $serve_request_from;
    return 418;
  }
  # END

  location / {
    error_page 418 = @uwsgi;
    return 418;
  }

  location @uwsgi {
    uwsgi_pass unix:///tmp/uwsgi-origserver.sock;
    include uwsgi_params;
    uwsgi_read_timeout 7200;
    client_max_body_size 20M;
  }

  location @proxy {
    proxy_pass https://other.server.com;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;
  }
}

這樣,在遷移完成之前,我需要在此處臨時添加的許多路由之間的重複最少。

相關內容