Q:

How to redirect a path to a port on the local machine?

Given 1000 servers (which may be started on demand before they are accessed) on the local machine that are bound to ports 8000 to 9000.
How to configure nginx so that the following request
http://my-domain.com/8505/foo/bar?id=hello

would be handled by
127.0.0.1:8505/foo/bar?id=hello

Is there a way to use a variable?
Edit: the original question talked about 5 servers, but I am looking for a mechanism to generalize the binding.

A:

Use a regex; (8[0-9][0-9][0-9]|9000) captures numbers from 8000 to 9000 to $1.
location ~ ^/(8[0-9][0-9][0-9]|9000)(.*)$ {
    proxy_pass http://127.0.0.1:$1$2?$args;
}

