Linux – iptables redirect range and exclude

iptableslinuxport-forwardingredirect

i have this iptables and working.

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 0:20 -j REDIRECT --to-port 8080 #bypass SSH
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 23:442 -j REDIRECT --to-port 8080 #bypass SSL
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 444:2082 -j REDIRECT --to-port 8080 #Cpanel SSL
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 2084:2086 -j REDIRECT --to-port 8080 #WHM SSL

any idea to change this into following condition in more simple rules:

Redirect ALL traffic to 8080

and Exclude Redirection if destination port match 22,443,2083 and 2087

thank you.

Update:

Multiports support up to 15 separate port Ref: Iptables packet filtering notes

so, i used another method to directly accept defined ports for example whois (port43)

iptables -t nat -A PREROUTING -i eth0  -p tcp -m multiport \
--dports 43 \
-j ACCEPT

Best Answer

One might argue this might work as an effort to concise your rules but it will not work as expected.

iptables -t nat -A PREROUTING -i eth0  -p tcp -m multiport --dports ! 22,443,2083,2087 -j REDIRECT --to-port 8080

the condition "-option a,b" is equivalent to "-option a OR -option b" which is exactly the 4 rules generated from the single one. However if "! -option a,b" is to be interpreted as "NOT (-option a OR -option b)", that is actually "(NOT -option a) AND (NOT -option b)" which just cannot be exploded into two rules.