How to use Linux and Iptables to route and masquerade ipv4 network traffic

You can use the shell script below to route and masquerade traffic coming to a network interface (“in_nic” variable) to another one (“out_nic” variable):

#!/bin/sh

set -e
set -u

in_nic=eth0
out_nic=eth1

# Flush old iptables rules
iptables -F; iptables -X
iptables -t nat -F; iptables -t nat -X
iptables -t mangle -F; iptables -t mangle -X

# Iptables policies (accept OUTPUT only)
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# Route and masquerade traffic 
iptables -A FORWARD -i "$in_nic" -o "$out_nic" -j ACCEPT
iptables -A FORWARD -i "$out_nic" -o "$in_nic" -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -t nat -A POSTROUTING -o "$out_nic" -j MASQUERADE

(the script is also available on gist: iptables-route-masquerade-traffic.sh)