Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic routing with NGINX

Tags:

nginx

I am an amateur of NGINX, I want to setup NGINX as a Reverse Proxy for my web server. I would like to know that the NGINX these things as listed below:

When a browser send request with URL: http://nginxproxy.com/client/1.2.3.4/, this request should be passed to the client with IP 1.2.3.4 http://1.2.3.4/, the browser should still show the URL nginxproxy/client/1.2.3.4/ And the same for:

  • nginxproxy.com/client/2.3.4.5 --> //2.3.4.5
  • nginxproxy.com/client/2.3.4.6 --> //2.3.4.6

All the others requests that doesn't mach the pattern should come to my default server myserver.

Can I do this by using NGINX?

After researching, I tried with the below configuration: But unlucky, It doesn't work. The address was changed to http:/1.2.3.4 on browser's address bar, instead of http:/nginxproxy.com/client/1.2.3.4 as expected.

server {
    listen       80;

    location ~ ^/client {       
        rewrite ^/client/?(.*) /$2 break;
        proxy_pass $scheme://$1;             
    }
    location / {
        proxy_pass http://myserver.com;
    }
}

Any help is much appreciated.

like image 919
Khate Avatar asked Apr 26 '26 22:04

Khate


2 Answers

Doing some more research and based on @Cole input, here is my answer:

location ~ ^/client/(?<site>[^/]+)/? {
    rewrite ^.*\/client\/(?<site>[^\/]+)\/?(.*) /$2 break; #passing all the remaining request URIs after <site> group to client server
    proxy_pass $scheme://$site;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host/client/$site; #this help to keep the address as it is on the browser's address bar
    proxy_set_header X-Forwarded-Proto $scheme;             
}

location / {
    proxy_pass $scheme://myserver.com
}
like image 199
Khate Avatar answered Apr 30 '26 01:04

Khate


server {
    listen  80;

    location /client/ {
        rewrite ^/client/(?<site>[^/]+)/? $scheme://$site;
    }

    location / {
        proxy_pass $scheme://myserver.com;
    }
}
like image 45
Cole Tierney Avatar answered Apr 30 '26 00:04

Cole Tierney



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!