3

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?

4

3 回答 3

1

用于获取 cookie 的正则表达式是错误的。我已将其更改为

"instance=([^;][^ ]+)(?:;|$)"

现在可以了。

编辑:这只是最终解决方案的一部分。对不起。还有一个问题。请参阅下面的评论。

于 2012-06-19T23:40:37.207 回答
0

它与您的问题无关,而是“proxy_connect_timeout”

“该指令为与上游服务器的连接分配了一个超时时间。有必要记住,这个超时时间不能超过 75 秒。”

于 2014-01-03T15:21:21.893 回答
-1

查看 Nginx 的地图模块

map $uri $proxy {
    /client1     http://127.0.0.1:8193/client1;
    /client2     http://127.0.0.1:8194/client2;
}

server {
    server_name my.domain.com;
    proxy_pass $proxy;
}

请注意,将 /clientX 附加到 proxy_pass URI 的末尾会从请求中删除 URI 的那部分(这对我来说似乎很合理,但可能不是您想要的)。

于 2012-06-24T06:22:02.803 回答