47

How can I forward requests coming in on port 80 to another port on the same linux machine?

I used to do this by changing nat.conf, but this machine that I'm using doesn't have NAT. What's the alternative?

1
  • No NAT whatsoever or just no nat.conf? Have you tried any iptables rules using NAT? Oct 11, 2011 at 22:38

3 Answers 3

55

You can accomplish the redirection with iptables:

iptables -A INPUT -i eth0 -p tcp --dport 80 -j ACCEPT

iptables -A INPUT -i eth0 -p tcp --dport 8080 -j ACCEPT

iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
6
  • +1. Being doing this for years Oct 12, 2011 at 0:33
  • 1
    How about on Windows Server?
    – Luc
    Aug 26, 2012 at 21:26
  • Oh man this is exactly what I was looking for, kudos!
    – neurosnap
    May 7, 2015 at 18:13
  • Didn't work for me at first, but was fine when I used sudo
    – mdiscenza
    Sep 6, 2016 at 17:58
  • 1
    what to do if no eth0 interface? why not use loopback interface?
    – harschware
    Jul 4, 2018 at 14:04
22

Just found myself in this question and couldn't find an easy way. Don't want to install Nginx in my machine to do this simple port forwarding.

Rinetd didn't work for me, no working package for my distro. I went for socat instead. Super simple:

socat TCP-LISTEN:80,fork TCP:127.0.0.1:5000

Must be ran as root to be able to listen on port 80.

2
  • Rinetd setup is easier I think.
    – johnshen64
    Oct 12, 2011 at 4:11
  • 1
    socat works perfectly!
    – viv
    Jun 6, 2019 at 12:43
10

You should look at using a reverse proxy, such as Nginx. For example, you might put something like this in your nginx.conf file:

server {
    listen         80;

    server_name    your_ip_address your_server_name

    access_log   /var/log/nginx/your_domain/access.log ;
    error_log    /var/log/nginx/your_domain/error.log info ;

    location / {
        proxy_pass  http://127.0.0.1:3000;   # pass requests to the destination
    }
}

2
  • 4
    Why? I don't neccessarily disagree but is there a good reason you wouldn't want this to just happen™ in the networking stack?
    – Oli
    Aug 19, 2016 at 13:13
  • 1
    @Oli This reverse proxy method will not affect numerous other virtual hosts on the server, which would occur if iptables would do it since iptables knows nothing of virtual hosts.
    – Ash
    Oct 14, 2017 at 22:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.