[LINUX] Port forwarding your web server using iptables

Overview

Describes how to forward (that is, port forwarding) the "host name: port number" of one web server to "another host: port number" on Linux. To realize this, use "iptables" that is installed as standard on CentOS and Ubuntu. The content introduced this time can probably be realized with firewalld etc. which is included by default in CentOS 7 or later, but as a result of searching for a method of port forwarding that does not depend on the environment as much as possible, I decided to use iptables. There are some articles that introduce port forwarding methods with iptables, but even if I tried those methods obediently, it did not work, and I was quite addicted to the realization, so I will summarize it again in this article. Only the http (https) protocol has been confirmed to work this time, but if it is TCP communication, it should work with other protocols (ssh, ftp, etc.).

Configuration you want to realize

fig1.png

Implementation by iptables

Execute the following command on the transfer source server

(1) PREROUTING chain

$ sudo iptables -t nat -A PREROUTING -p tcp \
                --dport 10080 -j DNAT \
                --to-destination 23.45.67.89:80

(2) POSTROUTING chain

$ sudo iptables -t nat -A POSTROUTING -p tcp \
                -d 23.45.67.89 --dport 80 \
                -j MASQUERADE

(3) FORWARD chain

$ sudo iptables -A FORWARD -p tcp \
                -d 23.45.67.89 --dport 80 \
                -j ACCEPT
$ sudo iptables -A FORWARD -p tcp \
                ! --syn -m state --state ESTABLISHED \
                -s 23.45.67.89 --sport 80 \
                -j ACCEPT

(4) OUTPUT chain

$ sudo iptables -t nat -A OUTPUT -p tcp \
                --dport 10080 -j DNAT \
                --to-destination 23.45.67.89:80

Recommended Posts

Port forwarding your web server using iptables
Turn your Android Smart Phone into a Web Server using python.
Build a web server on your Chromebook
Learning neural networks using Chainer-Creating a Web API server
HTTP server and HTTP client using Socket (+ web browser) --Python3
Web server construction commentary
About WOL port forwarding
One Liner Web Server
Ubuntu (18.04.3) Web server construction
Web application using Bottle (1)
Merry Christmas web server
Build a web API server at explosive speed using hug
Set up your own web server within your Pepper app project
Image Optimize on the server side using TinyPNG's Web API
Operate your browser using the Selenium Web Driver Python bindings
About WOL port forwarding
Try and learn iptablse, port forwarding
Linux ssh port forwarding (tunnel) settings
Port forwarding your web server using iptables
Including docker-nginx port forwarding on AWS Linux 2
Binding port forwarding to unix domain socket works