2

Is it possible to use Nginx to proxy from a URL like this:

http://example.com/service/1234/foo.php?...

to an internal service like this:

http://example.com:1234/foo.php?...

That is, extract a number from the URL, and use that as the port number to the same server?

rewrite seems limited to manipulating the part of the URL after the port, and I don't think proxy_pass can access a regex substring from it.

The specific problem I'm trying to solve is having my services all accessible on port 80, since various corporate and public networks block the exotic ports the services actually run on. So it has to be a reverse proxy, not a redirect.

This method works for a single port:

location /service/5010 {
  rewrite ^/service/5010/(.*)$ /$1 break;
  proxy_pass http://127.0.0.1:5010;
}

But the question is how to make the 5010 just a parameter extracted from the URL.

1

Something like

    location / {
       set $proxy_port 8080;
       if ($uri ~ "^/service/([0-9]+)/.*$")
       {
           set $proxy_port $1;
           rewrite ^/service/[0-9]+/(.*)$ /$1 break;
       }
       proxy_pass http://127.0.0.1:$proxy_port;
    }

at least it works for me on Nginx 1.6.2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.