I want to redirect port 80 on the loopback network interface so that accesses to that port actually go to port 8080.
I tried using the following command, but it only works if the application is listening on 127.0.0.1:8080, but not if it's listening on 127.1.2.3:8080.
sudo iptables -t nat -I OUTPUT -p tcp -o lo --dport 80 -j REDIRECT --to-ports 8080
I also tried adding --source 127.1.2.3/32 --destination 127.1.2.3/32
but it still doesn't work.
The redirection works if I open an application listening on 127.0.0.1:8080:
ssh remote -L127.0.0.1:8080:192.168.0.3:80
nc 127.0.0.1 80 # works
But it doesn't work if I open an application listening on 127.1.2.3:8080:
ssh remote -L127.1.2.3:8080:192.168.0.3:80
nc 127.1.2.3 80 # fails
nc: connect to 127.1.2.3 port 80 (tcp) failed: Connection refused
nc 127.1.2.3 8080 # works, so the application is still listening on 8080
How can I redirect the port 8080 on 127.x.x.x to the port 80 on the same IP?
Update: Motivation
I'm trying to use SSH to do the following port forwardings (127.1.2.3:80 → 192.168.0.3:80, and 127.1.2.4:80 → 192.168.0.4:80):
ssh remote -L127.1.2.3:80:192.168.0.3:80 -L127.1.2.4:80:192.168.0.4:80
Since port 80 is "privileged", ssh can't open it on localhost. There are several ways to circumvent that:
sudo ssh
, but I don't want to have to copy my ssh config and keys on the root account.- Use capabilities, but package updates may break this.
- Use a different port (e.g. 8080), that works but non-relative urls get broken.
- Reroute the privileged port to a non-privileged one, and that's what I'm trying to do. It works for a single redirection on 127.0.0.1, but it fails if I have redirections on IPs other than 127.0.0.1 (see above).