5

I would like to forward all incoming traffic from a certain port to another one using iptables. The problem is that prerouting doesn't work for traffic from localhost. This topic suggests a solution:

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

This solution does work for most cases. However, when I connect to http://myserver:443 where myserver resolves to an IP address that is hosted on the local machine, but is not 127.0.0.1 it seems to bypass both rules.

Is there a way to also catch forwards requests from the local machine that are done to the eth0 ip address?

2
  • Here's a really useful answer: unix.stackexchange.com/questions/111433/…
    – Wren T.
    May 16, 2014 at 4:39
  • Note that it can be dangerous to do the REDIRECTs blind like that, if the server is also acting as a firewall (as in one case when I wanted to do something like this), such a rule will manipulate all outgoing (routed) connections as well from the internal network to the external! In those cases you need to qualify them with one or several -d's (I couldn't find any more general solution)
    – BjornW
    Jul 9, 2023 at 8:57

1 Answer 1

4

Instead of doing -d 127.0.0.1 on the OUTPUT rule, you could do -o lo. This will match any traffic going through the loopback interface no matter what the destination is.

As a side note, even when you send to 'http://myserver:443', the traffic is still local, so it still goes through the loopback interface, even though it doesnt resolve to '127.0.0.1'.

1
  • This helped me (using -o lo) for REDIRECTing internal connections!
    – BjornW
    Jul 9, 2023 at 9:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .