Using Nginx for TCP/UDP Port Forwarding

nginx port forwardingtcp udp proxynginx stream moduleipv4 to ipv6 forwardingnginx configuration
Published·Modified·

Nginx (engine x) is a high-performance HTTP and reverse proxy server, as well as an IMAP/POP3/SMTP server. Since version 1.9.13, Nginx has supported port forwarding. Previously, we shared an article on installing rinetd on Linux for TCP port forwarding. While rinetd is simple to configure and easy to use, it unfortunately does not support UDP forwarding. If you need to support both TCP and UDP port forwarding, you can use Nginx.

Port Forwarding Diagram

Install Nginx

You can download the latest version of Nginx from the official http://nginx.org/ website and compile it. Note that the version must be greater than 1.9.1, and you must include the --with-stream module during compilation.

We will not introduce the compilation method here. This article uses a one-click script written by xiaoz to install Nginx, saving time and effort. Simply execute the following commands:

# Execute the command below and follow the prompts to complete the installation
wget https://raw.githubusercontent.com/helloxz/nginx-cdn/master/nginx.sh && bash nginx.sh
# After installation, execute the command below to make environment variables effective
source /etc/profile
# Execute the command below to check Nginx information
nginx -V

Nginx Version Check

Port Forwarding

Add the following configuration to nginx.conf, and use nginx -s reload to reload Nginx for it to take effect. Also, remember to allow the corresponding ports in the firewall/security group.

stream {
	# Forward port 12345 to port 3306 on 192.168.1.23
    server {
        listen 12345;
        proxy_connect_timeout 5s;
        proxy_timeout 20s;
        proxy_pass 192.168.1.23:3306;
    }
	# Forward UDP port 53 to port 53 on 192.168.1.23
    server {
        listen 53 udp reuseport;
        proxy_timeout 20s;
        proxy_pass 192.168.1.23:53;
    }
    # Forward IPv4 to IPv6
    server {
        listen 9135;
        proxy_connect_timeout 10s;
        proxy_timeout 30s;
        proxy_pass [2607:fcd0:107:3cc::1]:9135;
    }
}
  • listen: Enter the source port (the current server port). The default protocol is TCP, but you can specify UDP.
  • proxy_connect_timeout: Connection timeout duration.
  • proxy_timeout: Timeout duration.
  • proxy_pass: Enter the IP and port number of the forwarding target.

Note: Nginx can forward IPv4 packets to IPv6. IPv6 addresses must be enclosed in [].

Summary

Currently, tools that can implement port forwarding include rinetd, SSH, iptables, Nginx, and HAProxy. Among them, rinetd is the simplest to configure but does not support UDP forwarding, and the software has not been updated for several years. If Nginx is already installed on your server, consider using it for port forwarding.

This article references some content from:

Other Nginx-related articles: