iptables: How to "override" a port redirect?

by AppleDash   Last Updated May 29, 2015 23:00 PM

My setup is as follows:

I have a Linux server with two interfaces, eth0 and eth1. eth1 has an Internet connection through my normal LAN. eth0 is serving DHCP and the interface itself has an IP address of

I want to accomplish the following:

I want to have packets on port 80 originating from machines connected to eth0 to be redirected to port 80 on the routing machine itself, and response packets to of course be redirected back. That in itself is simple enough, but I have one more requirement. I would like clients on eth0 with certain IP addresses to be able to be exempt from this, and have port 80 packets routed as they normally would be. How can I do this? So far, I've done the following to redirect all port 80 packets from eth0 to the local machine. It is working, but I do not know how to do my second requirement.

iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination -i eth0

iptables -t nat -A POSTROUTING -p tcp -d --dport 80 -j SNAT --to-source

Answers 1

You need to just exit the PREROUTING table before it gets to the DNAT line:

iptables -t nat -I PREROUTING -p tcp -s <exempt ip> -j RETURN

This should insert (-I) a new rule to exit (-j RETURN) the routing table for any packet from the exempt IP (-s <exempt ip>) as the first rule, so it is hit before it gets to the DNAT rule.

(You might also need to do something similar on POSTROUTING, not sure.)

The other option is to create an IP set (man ipset) for the IPs that you want to exempt, and then add a inverted match to your DNAT and SNAT rules:

ipset create exempt hash:ip
ipset add exempt <exempt ip 1>
ipset add exempt <exempt ip 2>
ipset add exempt <exempt ip 3>
iptables -t nat -A PREROUTING -p tcp --dport 80 -m set ! --match-set exempt src -j DNAT --to-destination -i eth0

This is easier to manage because you can easily add or remove exempted IPs from the ipset without modifying iptables.

Darth Android
Darth Android
May 29, 2015 20:41 PM

Related Questions

Updated October 26, 2015 07:00 AM

Updated April 23, 2016 08:00 AM

Updated June 01, 2015 03:00 AM

Updated March 30, 2018 04:01 AM

Updated February 22, 2017 14:01 PM