Using Nginx for TCP/UDP Port Forwarding

Publish: 2018-07-15 | Modify: 2019-10-09

Nginx (engine x) is a high-performance HTTP and reverse proxy server, as well as an IMAP/POP3/SMTP server. After version 1.9.13, Nginx supports port forwarding. I have previously shared "Installing rinetd on Linux for TCP Port Forwarding", rinetd is simple to configure and easy to use, but unfortunately it does not support UDP forwarding. If you need to support both TCP and UDP port forwarding, you can use Nginx.

port_520

Installing Nginx

You can download the latest version of Nginx from the official website http://nginx.org/ and compile it yourself. Make sure the version is greater than 1.9.1, and you need to enable the "--with-stream" module during compilation.

I won't go into the details of the compilation process here. This article will directly use a one-click script written by Xiaoz to install Nginx, which saves time and effort. Just execute the following command:

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

snipaste_20180715_121831

Port Forwarding

Add the following configuration to "nginx.conf" and use "nginx -s reload" to reload Nginx to make it effective. Also, make sure to open the corresponding ports in the firewall/security group.

stream {
    # Forward port 12345 to port 3306 of 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 of 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": Specify the source port (the current server port), the default protocol is TCP, and you can specify UDP protocol.
  • "proxy_connect_timeout": Connection timeout
  • "proxy_timeout": Timeout
  • "proxy_pass": Specify the IP and port number of the forwarding target

Note: Nginx can forward IPv4 packets to IPv6. IPv6 IP addresses need to be enclosed in square brackets "[]".

Summary

Currently, there are several tools that can achieve port forwarding: rinetd, SSH, iptables, nginx, and haproxy. Among them, rinetd has the simplest configuration but does not support UDP forwarding. Moreover, this software has not been updated for several years. If you have Nginx installed on your server, you may consider using Nginx for port forwarding.

Some content in this article references:

Other Nginx-related articles:


Comments