How can I achieve port forwarding with IPTables?

0

I need to achieve the following scenario using IPTables:

Scenario Image Link

In this scenario we have a front end server with only one NIC with IP 1.2.3.4, and there are three other servers with IPs set to 172.20.20.20, 192.168.20.10 and 10.10.10.8.

The goal is to configure IP tables so that clients only connect to the front end server (1.2.3.4) and the request get forwarded based on the port, for example when the green client requests 1.2.3.4:8080, the request is sent to 10.10.10.8:8080, or if he sends a request to 1.2.3.4:443, his request is forwarded to 172.20.20.20:443 while preserving the original client's IP.

I need this IP as a part of user identification - based on the client's IPm different contents will be served.

I have already read these questions but it didn't help:

Jeremy Mc

Posted 2016-10-26T12:44:12.827

Reputation: 3

set he linux box as default gateway on all three servers. – Ipor Sircer – 2016-10-26T13:09:02.380

Answers

0

On the firewall/router - issue the following commands (assuming you want this to work on Port 80. The first provides the path to the webserver, the second corrects the outbound leg.

IPTABLES -t nat A PREROUTING -p tcp  -d REAL.WORLD.IP --dport 80  -j DNAT --to-destination INTERNAL.IP
IPTABLES -t nat -A POSTROUTING -s INTERAL.IP -p tcp --dport 80 -j SNAT --to-source EXTERNAL.IP

davidgo

Posted 2016-10-26T12:44:12.827

Reputation: 49 152

Dear @davidgo, Thanks for your answer but I think it doesn't satisfy the "while preserving the original client's IP." part of the question. Does it? – Jeremy Mc – 2016-11-14T09:05:06.060

Yes, it does. The first command rewrites the destination (not the from address), the second rewrites the from address - but only after its left the server, so the logging will show the correct source address. (I took these commands from a live system, so I'm quite sure of myself) – davidgo – 2016-11-14T09:34:27.563

I just realised that I did not specify the -t nat option in the rules above. This is required as well. – davidgo – 2016-11-14T18:42:34.503