How to do port forwarding/redirecting on Debian?

iptables -A PREROUTING -t nat -i eth3 -p tcp --dport 1234 -j DNAT --to-destination 192.168.57.25:80
iptables -A FORWARD -p tcp -d 192.168.57.25 --dport 80 -j ACCEPT
iptables -A POSTROUTING -t nat -s 192.168.57.25 -o eth3 -j MASQUERADE

The first one specifies that all incoming tcp connections to port 1234 should be sent to port 80 of the internal machine 192.168.57.25. This rule alone doesn’t complete the job because iptables denyes all incoming connections. Then we accept the incoming connection to port 1234 from eth3 which connect to the Internet with the publich IP by the second rule. We add the second rule in FORWARD chain to allow forwarding the packets to port 80 of 192.168.57.25.

EDIT: POSTROUTING added.

To keep track of the connection. otherwise the outside host would see the Internal IP 192.168.57.25 which he has no clue of.

EDIT2: Just got the hint that it should be --to-destination instead of --to (sry)


Thanks to Daywalker and Dánjal Salberg Adlersson. After hours of swearing, port forwarding with iptables finally works. (tested on Debian)

bash-script

#!/bin/bash

IPTBL=/sbin/iptables

IF_IN=eth0
PORT_IN=40022

IP_OUT=172.16.93.128
PORT_OUT=22

echo "1" > /proc/sys/net/ipv4/ip_forward
$IPTBL -A PREROUTING -t nat -i $IF_IN -p tcp --dport $PORT_IN -j DNAT --to-destination ${IP_OUT}:${PORT_OUT}
$IPTBL -A FORWARD -p tcp -d $IP_OUT --dport $PORT_OUT -j ACCEPT
$IPTBL -A POSTROUTING -t nat -j MASQUERADE