クッキーに基づいて proxy_pass と uwsgi_pass を切り替えますか?

クッキーに基づいて 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;
}

new_fe私のアプリケーション コードでは、値が「True」または「False」のいずれかであるという Cookie を設定しました。

値が「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;
  }
}

こうすることで、移行が完了するまでの間、ここで追加する必要がある多くのルート間での重複が最小限に抑えられます。

関連情報