42

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?

  • No NAT whatsoever or just no nat.conf? Have you tried any iptables rules using NAT? – Ben Swinburne Oct 11 '11 at 22:38
48

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
| improve this answer | |
  • +1. Being doing this for years – Alexander Pogrebnyak Oct 12 '11 at 0:33
  • 1
    How about on Windows Server? – Luc Aug 26 '12 at 21:26
  • Oh man this is exactly what I was looking for, kudos! – neurosnap May 7 '15 at 18:13
  • Didn't work for me at first, but was fine when I used sudo – mdiscenza Sep 6 '16 at 17:58
  • 1
    what to do if no eth0 interface? why not use loopback interface? – harschware Jul 4 '18 at 14:04
16

Just found myself in this question an 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 su to be able to listen on port 80.

| improve this answer | |
  • Rinetd setup is easier I think. – johnshen64 Oct 12 '11 at 4:11
  • socat works perfectly! – viv Jun 6 '19 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
    }
}

| improve this answer | |
  • 3
    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 '16 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 '17 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.