iptables port redirect not working for localhost

Solution 1:

PREROUTING isn't used by the loopback interface, you need to also add an OUTPUT rule:

iptables -t nat -I PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 8080
iptables -t nat -I OUTPUT -p tcp -o lo --dport 443 -j REDIRECT --to-ports 8080

Solution 2:

To redirect packets from localhost to another machine the rule:

 iptables -t nat -A OUTPUT -o lo -d 127.0.0.1 -p tcp --dport 443 -j DNAT  --to-destination 10.x.y.z:port

will work, BUT you also need to enable this option in the kernel:

sysctl -w net.ipv4.conf.all.route_localnet=1

Without that kernel setting it wont work.

Solution 3:

How about this?

iptables -t nat -A OUTPUT -d 127.0.0.1 -p tcp --dport 443 -j REDIRECT --to-port 8080