Nginx反向代理TCP协议【反代SSH端口】

2022年9月5日 940点热度
前言
需求缘由:
  • 当 VPS 在墙外时,SSH 的默认 22端口 是个非常敏感的端口,极为容易被墙主动干扰造成 SSH 登录失败。
  • 若是被墙扫描到正在连接 22端口 且墙的执行策略决定干扰你这个连接,则此时不仅 22端口 被阻断,而是所有端口都会被关闭会话。虽然一分钟内就能恢复其他端口畅通(22端 口仍被阻断),但一些保持会话的 Web 网页服务会异常需要重新刷新页面建立会话。
解决思路:
  • SSH使用非22端口
    • 1、根本性修改SSH配置文件,使用其他非 22 端口。
    • 2、SSH配置保持22端口不改变,使用其他端口转发到 22 端口。
注意事项:
  • Nginx 反代 TCP 协议必须使用 stream 模块,不能使用 http 模块,因 http 的 proxy_pass 无法承载TCP协议,所以关于stream的配置只能写到Nginx的主配置文件而不是某个新建网站的子配置文件。
更多相关知识:

Nginx反向代理TCP协议
  • 查询Nginx确认已安装模块"--with-stream",宝塔面板安装Nginx环境默认是带有stream模块的:
    root@vps:~# nginx -V
    nginx version: nginx/1.20.1
    built with OpenSSL 1.1.1k  25 Mar 2021
    TLS SNI support enabled
    configure arguments: --user=www --group=www --prefix=/www/server/nginx --add-module=srclib/ngx_devel_kit --add-module=srclib/lua_nginx_module --add-module=srclib/ngx_cache_purge --add-module=srclib/nginx-sticky-module --with-openssl=srclib/openssl --with-pcre=srclib/pcre-8.43 --with-http_v2_module --with-stream --with-stream_ssl_module --with-stream_ssl_preread_module --with-http_stub_status_module --with-http_ssl_module --with-http_image_filter_module --with-http_gzip_static_module --with-http_gunzip_module --with-ipv6 --with-http_sub_module --with-http_flv_module --with-http_addition_module --with-http_realip_module --with-http_mp4_module --with-ld-opt=-Wl,-E --with-cc-opt=-Wno-error --with-http_dav_module --add-module=srclib/nginx-dav-ext-module
  • stream代码模块追加到Nginx的主配置文件
    • 务必注意:stream 模块与 http 模块处于同一级!捋清楚 Nginx主配置文件 中你要添加位置的上一个 “}” 的定义范围,不要级别错误!否则将会报错以下信息:
      ERROR:
      nginx: [emerg] "stream" directive is not allowed here in /www/server/nginx/conf/nginx.conf:92
      nginx: configuration file /www/server/nginx/conf/nginx.conf test failed
    • 将以下 stream代码模块 追加到 Nginx主配置文件,可以添加最末尾,可以添加 http模块 前面,也可以将添加到 “worker_rlimit_nofile 51200 和 events 之间”:
      #stream模块与http模块处于同一级;这两个模块可以共存。
      stream {   
          upstream ssh{    
              server 127.0.0.1:22;       #源服务
              }
          upstream http{
              server 127.0.0.1:80;       #源服务
              }
          server {
              listen 22822;                    #监听代理主机的端口
              proxy_connect_timeout 1h;
              proxy_timeout 1h;
              proxy_pass ssh;            #转向的服务
              }
          server {
              listen 22880;                    ##监听代理主机的端口
              proxy_connect_timeout 1h;
              proxy_timeout 1h;
              proxy_pass http;            ##转向的服务
              }
      }
    • Nginx重载配置文件。
完成,开始使用!
    至此 SSH客户端 即可通过 VPS 的 22822端口 成功连接 SSH 服务!
    

书三拾

不积跬步无以至千里