Nginx实现UDP/TCP 端口数据转发 - Linux
Nginx 的 vhost(虚拟主机)目录通常用于存放 http 或 https 块中的域名配置(七层代理), UDP/TCP 端口转发属于 stream块(四层代理)
注意点:
不能在 vhost 目录下的文件中配置 UDP/TCP 转发。 vhost 文件只在处理 HTTP/HTTPS 请求时生效,无法监听纯 TCP/UDP 端口。
stream 配置必须独立存在。
需放在 nginx.conf 主配置文件中,或者在 conf.d/ 目录下创建一个独立于 vhost 的新文件(例如 stream_proxy.conf)。
域名在 Stream 中不起作用。 四层代理(Stream)只认 IP + 端口,不识别域名(yx.hongsin.cn)。只要流量到达服务器的 443/441 端口,Nginx 就会根据端口号进行转发,无论请求头里的域名是什么。
TCP 转发:从 Nginx 1.9.0 版本开始支持。
UDP 转发:从 Nginx 1.9.13 版本开始正式支持。编译模块:
需要启用 ngx_stream_core_module 模块, 在编译安装时,必须添加 --with-stream 参数,如果没添加需要添加上·
查看当前Nginx参数:
/usr/local/nginx/sbin/nginx -V
nginx version: nginx/1.26.3
built by gcc 14.3.1 20251022 (Red Hat 14.3.1-4) (GCC)
built with OpenSSL 1.1.1w 11 Sep 2023
TLS SNI support enabled
configure arguments: --user=www --group=www --prefix=/usr/local/nginx --add-module=/usr/local/nginx/src/ngx_devel_kit --add-module=/usr/local/nginx/src/lua_nginx_module --add-module=/usr/local/nginx/src/ngx_cache_purge --add-module=/usr/local/nginx/src/nginx-sticky-module-ng-1.3.0 --with-openssl=/usr/local/nginx/src/openssl --with-pcre=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-http_auth_request_module --add-module=/usr/local/nginx/src/ngx_http_substitutions_filter_module-master --with-ld-opt=-Wl,-E --with-cc-opt=-Wno-error --with-ld-opt=-ljemalloc --with-http_dav_module --add-module=/usr/local/nginx/src/nginx-dav-ext-module --with-http_v3_module在http上面include 转发配置文件如下:
cat stream_proxy.conf
stream {
$bytes_received $session_time';
log_format basic '$time_local|$remote_addr|$protocol|$status|$bytes_sent|$bytes_received|$session_time|$upstream_addr|$upstream_bytes_sent|$upstream_bytes_received|$upstream_connect_time';
# TCP 443
server {
listen 443;
proxy_pass x.x.x.x:443;
proxy_connect_timeout 5s;
proxy_timeout 30s;
access_log /www/wwwlogs/tcp_443_access.log basic;
error_log /www/wwwlogs/tcp_443_error.log;
}
# TCP 441
server {
listen 441;
proxy_pass x.x.x.x:441;
proxy_connect_timeout 5s;
proxy_timeout 30s;
access_log /www/wwwlogs/tcp_441_access.log basic;
error_log /www/wwwlogs/tcp_441_error.log;
}
# UDP 443
server {
listen 443 udp;
proxy_pass x.x.x.x:443;
proxy_timeout 30s;
access_log /www/wwwlogs/dup_443_access.log basic;
error_log /www/wwwlogs/udp_443_error.log;
}
# UDP 441
server {
listen 441 udp;
proxy_pass x.x.x.x:441;
proxy_timeout 30s;
access_log /www/wwwlogs/udp_441_access.log basic;
error_log /www/wwwlogs/udp_441_error.log;
}
}
Tag标签:「nginx 编译 代理 udp tcp Stream」更新时间:「2026-03-08 19:50:08」阅读次数:「36」