I'm trying to do a reverse proxy with Nginx based on the URL. I want http://mydomain.example.com/client1/... to be redirected to http://127.0.0.1:8193/.... I have tried many ways, and none of them worked. Please note that the application can make redirections. These are the configuration files of my last solution :
default
server {
    listen                  80;
    server_name             mydomain.example.com;
    location / {
            set $instance none;
            if ($request_uri ~ ^/(.*)/$) {
                    set $instance $1;
            }
            set $no_cookie true;
            if ($http_cookie ~ "instance=([^;] +)(?:;|$)") {
                    set $instance $1;
                    set $no_cookie false;
            }
            if ($no_cookie = true) {
                    add_header Set-Cookie "instance=$instance;Domain=$host;Path=/";
                    rewrite ^ / break;
            }
            include instances.conf;
    }
instances.conf
proxy_redirect                 off;
proxy_set_header               Host $host;
proxy_set_header               X-Real-IP $remote_addr;
proxy_set_header               X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout          90;
proxy_send_timeout             60;
# Installation of language packs, etc. can take a long time
proxy_read_timeout             10800;
if ($instance = client1) {
    proxy_pass http://127.0.0.1:8193;
}
if ($instance = client2) {
    proxy_pass http://127.0.0.1:8194
}
...
When the browser requests http://mydomain.example.com/client1/, Nginx should set a cookie named instance with the value client1 then redirect the traffic to the appropriate proxy. For subsequent queries, it should use this cookie to make redirection. The problem I have is it never sets the $instance variable to client1. Don't forget that the application has no idea of the prefix /client1.
Do you have an idea? Do you know of a better solution?