Nginx proxy_pass two ports into subfolders

nginxproxypassreverse-proxywebsocket

So I had my last "reverse proxy" problem fixed regarding "mapping" a port to a subfolder Thanks again to this awesome community.

I have been able to work with this solution for a while but now I am facing a new problem. The situation is:

There is a webpage setup (using nginx) with this url http://test.domain.com:8042/view.html. I needed for various reasons that this port turns into a subfolder and achieved it (with help) and gained http://test.domain.com/view/view.html.

The proxy_pass for this is:

location ~/view(.*)$ {
proxy_set_header X-Real-IP  $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $host:$server_port;
proxy_pass http://test.domain.com:8042$1;

This works amazing. I can access the page over http://test.domain.com/view/view.html. There are several websockets on that page, one also has the port 8042. This one works fine. However, the other websockets have different ports, e.g. 8159. I have added an respective proxy_pass to the nginx config:

location ~/cantrace(.*)$ {
proxy_set_header X-Real-IP  $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $host:$server_port;
proxy_pass http://test.domain.com:8159$1;

From Javascript this websocket is called via

my_websocket = new WebSocket('ws://test.domain.com/cantrace/ws');

but that does not work. Neither does

my_websocket = new WebSocket('ws://test.domain.com/view/cantrace/ws');

What does work, however, is

http://test.domain.com:8042/view.html

and then it loads the other websockets on view.html with

my_websocket = new WebSocket('ws://test.domain.com/cantrace/ws');

which did previously not work.

So clearly the double proxy_pass with /view and /cantrace is a problem here. Is there a way to work around this with nginx?

Thank you very much!

Patrick

Best Answer

I had such a setup to access two servers behind a reverse proxy, I believe your proxy_passs directive is missing a trailing /, this was my setup:

       location /server1 {
               proxy_pass http://server1:8081/;
               proxy_buffering off;
       }
       location /server2 {
               proxy_pass http://server2:8082/;
               proxy_buffering off;
       }

In your case, this would translate to:

proxy_pass http://test.domain.com:8042/$1;