环境

系统:Centos7
服务器:腾讯云轻量香港

目的

通过nginx proxy ssh端口来达到安全、加速的效果。

部署

实现此功能需要将stream模块编译进来,依照官方文档得知:

The ngx_stream_core_module module is available since version 1.9.0. This module is not built by default, it should be enabled with the --with-stream configuration parameter.

官方文档指出,在1.9.0版本后可以使用stream模块,但此模块不是默认编译进去的,所以需要我们在编译安装nginx的时候加上它--with-stream

配置

官方的Example

Example Configuration
worker_processes auto;

error_log /var/log/nginx/error.log info;

events {
    worker_connections  1024;
}

stream {
    upstream backend {
        hash $remote_addr consistent;

        server backend1.example.com:12345 weight=5;
        server 127.0.0.1:12345            max_fails=3 fail_timeout=30s;
        server unix:/tmp/backend3;
    }

    upstream dns {
       server 192.168.0.1:53535;
       server dns.example.com:53;
    }

    server {
        listen 12345;
        proxy_connect_timeout 1s;
        proxy_timeout 3s;
        proxy_pass backend;
    }

    server {
        listen 127.0.0.1:53 udp reuseport;
        proxy_timeout 20s;
        proxy_pass dns;
    }

    server {
        listen [::1]:12345;
        proxy_pass unix:/tmp/stream.socket;
    }
}

创建配置

参照官方的Example,我们来创建 or 修改自己的配置文件。

http {}
stream {
    upstream ssh {
        hash $remote_addr consistent;

        server IP:PORT;
    }
     server {
        listen 12345;
        proxy_connect_timeout 60s;  // 注意此处不要把proxy配置放到location {}里面,否则会报错。
        proxy_timeout 60s;
        proxy_pass ssh;
    }

}
  /usr/local/nginx/sbin/nginx -t
 /usr/local/nginx/sbin/nginx -s reload
[root@LWS-QHK-NODE vhost]# ss -anptu | grep 12345
 tcp    LISTEN     0      511       *:12345                 *:*                   users:(("nginx",pid=22190,fd=16),("nginx",pid=21964,fd=16))

测试

Nginx使用反向代理转发SSH服务

参考文献

stream 官方文档

文章目录