Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx reverse proxy: How to implement?

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?

like image 220
user1457432 Avatar asked Jul 16 '26 11:07

user1457432


1 Answers

The regex used to get the cookie was wrong. I have changed this to

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

and it works now.

Edit: It's only a part of the solution finally. I'm sorry. There is still a problem. See my comment below.

like image 137
user1457432 Avatar answered Jul 19 '26 12:07

user1457432



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!