12

How can I setup nginx to reverse proxy a single folder to one server and the rest of root to a different server?

The root "/" is managed by CMS while the "other" is my own programs (independent of the CMS).

Here is my current configuration

server {
    listen  80;
    server_name www.example.com;
    rewrite     ^   https://$server_name$request_uri? permanent;
}

server {
    listen   443;
    ... <ssl stuff> ...

    server_name www.example.com;

    location /other {
        proxy_pass http://192.168.2.2/other ;
    }

    location / {
        proxy_pass http://192.168.1.1;
    }
}
user3160945
  • 121
  • 1
  • 1
  • 6

2 Answers2

19

reference to nginx docs:

http://wiki.nginx.org/HttpCoreModule#location

http://wiki.nginx.org/HttpProxyModule#proxy_pass

You should change the other location to this:

location /other/ {
    proxy_pass http://192.168.2.2/other/ ;
}

Note the trailing /. It actually make a difference since it gets proxy_pass to normalize the request. I quote:

when a request is passed to the server, the part of a normalized request URI matching the location is replaced by a URI specified in the [proxy_pass] directive.

This should help those that find this page.

iansheridan
  • 431
  • 3
  • 8
  • Thank you soo much. I needed a way to use nginx as a reverse proxy but wanted the URL to be rewrited/prefixed with a folder. This works like a charm (without the folder in the location part ofcourse)! – Dillen Meijboom Jul 21 '17 at 17:04
  • Thanks, it worked for me, i was redirect example.com/admin to another nginx in a docker container. Is there a way to remove tail slash at the end of url `example.com/admin/`, it is appended all the time. – Alexander Kim Oct 14 '18 at 10:48
0
You needs to use this code , i think it work

server {
    listen  80;
    server_name www.example.com;
    rewrite     ^   https://$server_name$request_uri? permanent;
}

server {
    listen   443;
    ... <ssl stuff> ...

    server_name www.example.com;

    location = /other {
        proxy_pass https://192.168.2.2/other ;
    }

    location / {
        proxy_pass https://192.168.1.1;
    }
}
Mayur Kothari
  • 254
  • 2
  • 4