大网数据广告活动
服务器运维问答

Nginx redirect to different IP based on port number

· 52CE 我爱测

I have multiple HTTP servers (IoT stuff) connected to a Raspberry Pi with a Nginx instance. I want to proxy the access to those servers through Nginx by using its IP address and multiple ports: 192.168.1.100:8080 -> 192.168.2.80 …

问题原文

原帖链接 · rslite · CC BY-SA 4.0

I have multiple HTTP servers (IoT stuff) connected to a Raspberry Pi with a Nginx instance. I want to proxy the access to those servers through Nginx by using its IP address and multiple ports:

192.168.1.100:8080 -> 192.168.2.80
192.168.1.100:8081 -> 192.168.2.81
...

I have this configuration in Nginx which works:

server {
    listen  8080;
    location / {
        proxy_pass http://192.168.2.80;
        ..... extra config
    }
}

However, I don't want to write a separate config entry for every possible address since there can be many and I have to add for each some extra config settings which I don't want to repeat. I know I can add multiple listen ports in the same server configuration, but is there any way to extract the port number and use it to rewrite the proxy_pass address?

已采纳解答

原帖链接 · Tero Kilkanen · CC BY-SA 4.0

EDIT:

An automatic port -> IP address mapping might work like this:

map $server_port $upstream {
    "~^80(?<dest>[0-9+])$"   192.168.2.$dest;
}

Here a regular expression capture is used to capture the latter part of port number into variable, and then the variable is used in the destination string.


I haven't tested this myself, but it should work.

First, you need to define a map in the http level, which maps port numbers to proxy endpoints:

map $server_port $upstream {
    8080     192.168.2.80;
    8081     192.168.2.81;
    8082     192.168.2.82;
    ...
}

You might need to add a default line to the map.

Then, in the server level, you add the following:

listen 8080;
listen 8081;
listen 8082;

location / {
    proxy_pass http://$upstream;
}

This setup makes a single server block listen to multiple ports, and when using the mapped variable as proxy_pass destination, it will make nginx send the request to desired destination.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2019-01-30)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。