Home > database >  nginx reverse proxy depends on requested port
nginx reverse proxy depends on requested port

Time:09-22

I want to listen port a range, and bind it with reverse proxy with incremental value(10000).

In example, i want to listen and bind it to this values:

example.com:20000 -> http://0.0.0.0:30000
example.com:20010 -> http://0.0.0.0:30010
example.com:20200 -> http://0.0.0.0:30200

my nxing conf:

server {
  listen        20000-20200;
  server_name   example.com;
  
  location / {
    proxy_pass  http://0.0.0.0:$server_port; ## << I want increment this port with 10000
  }
}

How can i do this?

CodePudding user response:

Wow, I didn't know that nginx allows to listen on port range. I didn't find it in documentation, but when I checked it myself, it is really working as expected.

Well, back to the question. Without additional modules nginx doesn't have any built-in mathematics. However, since all you need is the only one digit replacing, you can do it via regex capture group and concatenation of strings:

map $server_port $proxy_port {
    "~\d(\d{4})"    3$1;
}
server {
    listen          20000-20200;
    server_name     example.com;
    location / {
        proxy_pass  http://0.0.0.0:$proxy_port;
    }
}

If you're using OpenResty (or build nginx yourself with lua-nginx-module), you can use real mathematics with LUA code within the nginx config:

server {
    listen          20000-20200;
    server_name     example.com;
    location / {
        set_by_lua_block $proxy_port { return ngx.var.server_port   10000 }
        proxy_pass  http://0.0.0.0:$proxy_port;
    }
}
  • Related