Websocket reverse proxy using variable port

What I’m trying to do: I’m trying to set up a reverse proxy where players can can connect to their respective game server by including the port in the path (ex: ws://server.com/PORT). All the game server instances are on the same digital ocean droplet

Where I’m stuck: upstream_addr doesn’t seem to get set when I set proxy_pass using the port from the path, but when I hard code a port into the proxy_pass url it works as expected.

What I’ve already tried:
Logs
The first row is trying to connect with proxy_pass http://localhost:$1 the second row is when I just set it to proxy_pass http://localhost:3001 Notice how the second row has “[::1]:3001” which is where I print out upstream_addr

[01/Jul/2025:06:13:33 +0000] 76.168.82.52 - - "server.com/3001" 499 0 "-" "-" "-" Proxy: "localhost:3001" "-"
[01/Jul/2025:06:14:23 +0000] 76.168.82.52 - - "server.com/3001" 101 216 "-" "-" "-" Proxy: "localhost:3001" "[::1]:3001"

nginx.conf

        underscores_in_headers on;

        location ~ ^/(\d+)$ {
            proxy_pass http://localhost:$1;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
1 Like

Hey @finalturn! I have tried to recreate a similar config to yours here https://tech-playground.com/snippet/glistening-mellow-labrador/ and I can’t seem to replicate the issue. Can you have a look and see if it helps out or try to tweak it to make it closer to your environment?

3 Likes

Okay I slapped your config file into my server and it worked! The key difference between yours and mine is that I was using proxy_pass http://localhost:$1; and you were using proxy_pass http://127.0.0.1:$1; (is this expected behavior? :sweat_smile:)

Thanks a bunch for taking time to help me with this!

1 Like