By accessing the website and accepting the Cookie Policy, you agree to use the cookies provided by the Site in accordance with to analyze traffic, remember your preferences, and optimize your experience.
Nginx反向代理之端口转发TCP/UDP
2020-09-25 14:18:31    223    0    0
emengweb

Nginx反向代理之端口转发

 

 

安装Nginx

可以自行去官方http://nginx.org/下载最新版本Nginx编译安装,注意版本一定要大于1.9.1,编译的时候需要--with-stream这个模块支持。

编译方法这里就不介绍了,这篇文章直接使用一键脚本安装Nginx,省时、省力,直接执行下面的命令即可。

#执行下面的命令,根据提示完成安装
wget https://raw.githubusercontent.com/helloxz/nginx-cdn/master/nginx.sh && bash nginx.sh
#安装完成后执行下面的命令让环境变量生效
source /etc/profile
#执行下面的命令查看nginx信息
nginx -V

端口转发

nginx.conf添加如下配置,并使用nginx -s reload重载nginx使其生效,同时注意防火墙/安全组放行对应的端口。

stream {
    #将12345端口转发到192.168.1.23的3306端口
    server {
        listen 12345;
        proxy_connect_timeout 5s;
        proxy_timeout 20s;
        proxy_pass 192.168.1.23:3306;
    }
    #将udp 53端口转发到192.168.1.23 53端口
    server {
        listen 53 udp reuseport;
        proxy_timeout 20s;
        proxy_pass 192.168.1.23:53;
    }
    #ipv4转发到ipv6
    server {
        listen 9135;
        proxy_connect_timeout 10s;
        proxy_timeout 30s;
        proxy_pass [2607:fcd0:107:3cc::1]:9135;
    }
}
  • listen:后面填写源端口(也就是当前服务器端口),默认协议为TCP,可以指定为UDP协议
  • proxy_connect_timeout:连接超时时间
  • proxy_timeout:超时时间
  • proxy_pass:填写转发目标的IP及端口号

注意:nginx可以将IPV4的数据包转发到IPV6,IPV6的IP需要使用[]括起来。

上一篇: WebSocket使用Nginx反向代理解决Wss服务问题

下一篇: Nginx自建CDN 第三篇

223 人读过
文档导航