如何将 NGINX 配置为不同端口号的反向代理?

Ole*_*Ole 20 nginx

I have NGINX configured like this as a reverse proxy for http requests:

server {
    listen 80;
    server_name 203.0.113.2;

    proxy_set_header X-Real-IP  $remote_addr; # pass on real client IP

    location / {
        proxy_pass http://203.0.113.1:3000;
    }
}
Run Code Online (Sandbox Code Playgroud)

我还想代理 ssh(端口 22)请求。我可以在同一个配置文件中添加另一个这样的服务器块吗:

server {
    listen 22;
    server_name 203.0.113.2;

    proxy_set_header X-Real-IP  $remote_addr; # pass on real client IP

    location / {
        proxy_pass http://203.0.113.1:22;
    }
}
Run Code Online (Sandbox Code Playgroud)

这样最终的结果是这样的:

server {
    listen 80;
    server_name 203.0.113.2;

    proxy_set_header X-Real-IP  $remote_addr; # pass on real client IP

    location / {
        proxy_pass http://203.0.113.1:3000;
    }
}
server {
    listen 22;
    server_name 203.0.113.2;

    proxy_set_header X-Real-IP  $remote_addr; # pass on real client IP

    location / {
        proxy_pass http://203.0.113.1:22;
    }
}
Run Code Online (Sandbox Code Playgroud)

TIA,
奥莱

cns*_*nst 17

所述SSH协议不是基于HTTP,并且,因此,无法通过常规的代理proxy_passngx_http_proxy_module

然而,最近,从nginx 1.9.0(在 2016 年 4 月 26 日发布为 1.10.0 的稳定版本)开始,nginx 确实获得了对TCP 流代理的支持,这意味着如果您有足够新的 nginx 版本,实际上,您可以使用它代理 ssh 连接(但是,请注意,您无法向X-Real-IP代理连接添加类似 的任何内容,因为这不是基于 HTTP 的)。

有关更多信息和示例,请查看:


小智 11

由于 Nginx 版本 1.9.0,NGINX 支持 ngx_stream_core_module 模块,它应该通过 --with-stream 启用。当启用流模块时,它们可以通过 ssh 协议 tcp 代理

stream {
    upstream ssh {
        server 192.168.1.12:22;
    }
        server {
        listen        12345;
        proxy_pass    ssh;

    }

}
Run Code Online (Sandbox Code Playgroud)

https://www.nginx.com/resources/admin-guide/tcp-load-balancing/