Iptables Port Forwarding – How to Forward Packets with Destination Port 80 from eth0 to eth1

iptableslinuxlinux-networkingnat;port-forwarding

I've http and https traffic coming from several machines to my eth0 on my Linux machine, but I want to forward these traffic to eth1 which has the access to the internet. And do the complimentary operation of traffic coming from 80 and 443 to be routed from eth1 to eth0 so that they reach the machines that created the web requests.

I've tried the following iptables commands, but it didn't help:

iptables -A FORWARD -p tcp --dport 80 -o eth1 -j ACCEPT
iptables -A FORWARD -p tcp --sport 80 -o eth0 -j ACCEPT

I'm not sure how to go about this.

=====================

Output of ip addr show

$ /sbin/ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast qlen 1000
    link/ether <mac_address_of_eth0> brd ff:ff:ff:ff:ff:ff
    inet 10.10.12.131/24 brd 10.10.12.255 scope global eth0
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast qlen 1000
    link/ether <mac_address_of_eth1> brd ff:ff:ff:ff:ff:ff
    inet 172.16.1.1/24 brd 172.16.1.255 scope global eth1

Best Answer

First of, this is a very similar question to iptables forwarding between two interface.

That being said, you want your host to become a gateway, but more specific, only to protocols HTTP and HTTPS (80 / 443). To achieve this, you should:

  1. Be able to forward traffic between this two interfaces
  2. Forward packets with destination port 80 (HTTP)
  3. Forward packets with destination port 443 (HTTPS)
  4. As iptables (netfilter) is a stateless packet filtering system, accept packets that are comming back
  5. Source NAT (change the originating IP address) to your host's IP

Translated to iptables:

echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -A FORWARD -i eth0 -o eth1 -p tcp --dport 80  -j ACCEPT
iptables -A FORWARD -i eth0 -o eth1 -p tcp --dport 443 -j ACCEPT
iptables -A FORWARD -i eth1 -o eth0 -m state --state ESTABLISHED,RELATED \
   -j ACCEPT
iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE

Provided the other hosts on your network are using your host to reach internet (meaning your linux box behaves as a gateway).