Basierend auf Cookie zwischen proxy_pass und uwsgi_pass wechseln?

Basierend auf Cookie zwischen proxy_pass und uwsgi_pass wechseln?

Mein Nginx-Server ist derzeit so eingerichtet, dass alle Anfragen über Folgendes bearbeitet werden uwsgi_pass:

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

In meinem Anwendungscode habe ich ein Cookie namens gesetzt, new_fedessen Wert entweder „True“ oder „False“ ist.

Wenn der Wert „True“ ist, möchte ich stattdessen proxy_passauf einen anderen externen Server zugreifen, aber nur für bestimmte Routen. So etwas wie das FolgendePseudocode:

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

Wie kann ich das machen? Ich bin noch relativ neu bei nginx, also entschuldigen Sie bitte die Frage, wenn es etwas Einfaches ist, das ich übersehe.

Antwort1

Als vorübergehende Lösung sollte dies funktionieren:

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
}

Antwort2

Ich habe mich etwas genauer mit Karten befasst und bin auf diese Lösung gestoßen, die zu funktionieren scheint (verwendet sowohl die Vorschläge von @womble als auch von @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;
  }
}

Auf diese Weise habe ich eine minimale Duplizierung über die vielen Routen hinweg, die ich hier in der Zwischenzeit hinzufügen muss, bis diese Migration abgeschlossen ist.

verwandte Informationen