48

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?

Scott Pack
  • 14,717
  • 10
  • 51
  • 83
Nohsib
  • 581
  • 1
  • 4
  • 3

3 Answers3

56

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
Eddie C.
  • 487
  • 1
  • 3
  • 12
Thomas Vincent
  • 1,090
  • 6
  • 13
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.

Tansc
  • 3
  • 2
alfetopito
  • 321
  • 2
  • 4
11

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
    }
}

Eddie C.
  • 487
  • 1
  • 3
  • 12
Tilo
  • 391
  • 1
  • 5
  • 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 '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