0

I am tunneling some remote cameras throw SSH to a VPS. I want to be able to pass the port number over the url, and nginx proxy it to the localhost:'that port'.

Pretty much this:

http://test.doman.com/1234/ -> localhost:1234/something/

I found a question pretty similar, but I was not able to understand it and modify to my needs.

NGINX Dynamic Port proxy_pass

UPDATE:

I tried to modify the example in many ways (below is one that more made sense) but every time I try a curl, I get a page 500 instead of the desired port.

server {
    listen          80;
    server_name     my.domain.com;

    location ~ ^/cam/([0-9]+)$ {
        set         $port   $1;
        proxy_pass  http://localhost:$port/cgi-bin/mjpg/video.cgi?channel=1&subtype=1;
    }
}

UPDATE 2

Apparently my rule config is right (rewrite the whole nginx.conf just to be sure) but I am still getting a 502 Bad Gateway message. I can curl localhost:8080 from my external server, and it reaches my camera page, but I can't redirect it using nginx.

http {
    server {
        listen 80;
        root /var/www/;
        location ~ ^/cam/([0-9]+) {
            set $port_num $1;
            # Debug my variable
            #return 200 $port_num;
            proxy_pass http://localhost:$port_num;
        }
    }
}
events { }

UPDATE 3

I did look at the log file (thanks for the suggestion), and notice that NGINX was not able to resolve localhost (???).

2020/10/07 13:53:39 [error] 1997#1997: *4 no resolver defined to resolve localhost, client: 127.0.0.1, server: , request: "GET /cam/8080 HTTP/1.1", host: "localhost"

I replace the localhost string to 127.0.0.1 and tried again. This time I get a 404 message from the curl but no error in my log.

<html><body><h1>404 Not Found</h1></body></html>

IamRichter
  • 1
  • 1
  • 3

1 Answers1

0

Alright. I hope this example may be helpful for someone.

location ~ ^/cam/([0-9]+)/ {
            set $port_num $1;
            proxy_pass http://localhost:$port_num/;
        }

If you are confused about what is happening there (as I was before read the docs), the location uses a regular expression to find anything that start with /cam/ (after the url) and get what comes after it (the ([0-9]+) tell nginx to get only it's numbers, a string would go 404). The set allow to create a variable (just to make things more clear) and the proxy_pass redirect the url.

IamRichter
  • 1
  • 1
  • 3