Help me understand iptables

Can someone tell me what every option in this command does.

iptables -t nat -A PREROUTING -p TCP --dport 80 -j REDIRECT --to-port 3128

And the difference between that and:

iptables -t nat -A PREROUTING -i eth0 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 3128

What I want is exactly the first command but I want to be able to specify the input interface and the output interface. (I want to make sure that the entering traffic on a multi-interface situation to always be redirected to the same interface it was inputed from).

-t is the target table in this case "nat"
-A is append in this case append to the PREROUTING chain
-p is protocol here its "tcp"
--dport is destination port ,"80" in this case
-j is jumpt to target , target here is "REDIRECT"
--to-port is pretty self explanatory

in the second command you have -i etho
-i is interface, eth0 in this case
-m is match , matches tcp in this case

in the 1st statement all local (?) tcp traffic to port 80 will be redirected to port 3128 (i think, not entirely sure as you have not specified a source network eg: -s 192.168.x.x/xx )

the second will redirect all local (?) incoming tcp traffic on eth0 and on port 80 to port 3128 (again no -s specified).
https://www.karlrupp.net/en/computer/nat_tutorial has a nice little writeup on this.

i am not a iptables guru, just know a thing or 2 (and that may be wrong as well)

1 Like

Almost right, all nat'd traffic with port 80 as it's destination will have it's destination changed to port 3128 in the PREROUTING chain of the nat table, i.e before the kernel decides what route to send it down.

1 Like

The difference between -A and -I is very important in iptables. A good example is where your last rule in the chain is "DROP". If you append a rule after that using -A it will never be read as the rules are read sequentially. With -I you can also specify the line number to insert it above eg:

iptables -I INPUT 13 -i eth0 -p tcp -m tcp --dport 80 -j ACCEPT

This would insert the rule into line 13. To view the current ruleset with line numbers this is my preferred command:

iptables -nvL --line-numbers

Remember to use iptables-save > [filename] before making changes and revert using iptables-restore < [filename]