¿Cambiar entre proxy_pass y uwsgi_pass según la cookie?

¿Cambiar entre proxy_pass y uwsgi_pass según la cookie?

My nginx server is currently setup to serve all requests via uwsgi_pass:

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

In my application code, I've set a cookie called new_fe whose value is either "True" or "False".

When the value is "True", I want to instead proxy_pass to another external server, but only for specific routes. Something like the following pseudo code:

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

How can I do this? I'm still a bit new to nginx, so please pardon the question if it's something simple I'm missing.

Respuesta1

As a temporary solution this should work:

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
}

Respuesta2

I looked into maps a bit more and came up with this solution, which seems to work (uses both @womble's and @alexey-ten's suggestions):

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

De esta manera, tengo una duplicación mínima en las muchas rutas que necesitaré agregar aquí mientras tanto, hasta que se complete esta migración.

información relacionada