Nginx反向代理取决于请求的端口 [英] nginx reverse proxy depends on requested port

查看:22
本文介绍了Nginx反向代理取决于请求的端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想监听一个范围,并将其与增量值(10000)的反向代理绑定。

在示例中,我希望侦听并将其绑定到以下值:

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

我的nxing会议:

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
  }
}

如何执行此操作?

推荐答案

哇,我不知道ngix允许侦听端口范围。我在documentation中没有找到,但是当我自己检查的时候,它真的可以正常工作。

那么,回到问题上来。如果没有额外的模块,nginx没有任何内置的数学。但是,因为您只需要替换一位数字,所以您可以通过正则表达式捕获组和字符串连接来完成:

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

如果您正在使用OpenResty(或使用lua-nginx-module自己构建nginx),您可以在nginx配置中对Lua代码使用真正的数学:

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

这篇关于Nginx反向代理取决于请求的端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆