Unix & Linux
iptables port-forwarding json
Updated Fri, 29 Jul 2022 15:48:17 GMT

Redirect domains to different ports on same machine

I used the following command to redirect 80 to 3000. All the requests that come, from any domain, are redirected to 3000:

sudo iptables -t nat -I PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 3000

Having to processes: one that listens on 80001 and another one that listens on 8002 how can I link two domains to the two ports?

Is it possible to have a JSON configuration like below?

       "port": 8001,
       "domains": ["example.com", "example2.com"] 
       "port": 8002,
       "domains": ["domain.com", "domain2.com"] 

So, domain.com, domain2.com will send their requests to the process that listens on 8002 and the other two domains on 8001?


Usually you would have to setup your web server with virtual hosts and maybe mod_proxy (for Apache).

However, I would suggest that you use a reverse proxy such as haproxy to take care of that. Setup Haproxy so that it listens to port 80 and direct your traffic to your webservers using ACLs on the domain name. Setup your webserver with virtual hosts that listen to and (if haproxy runs on the same server).

Pretty simple setup.

Look at this example. It's for putting haproxy in front of Docker containers, but you can adapt the configuration to suit your needs.

Comments (2)

  • +0 – And how to use it? Can you add an example? — Aug 19, 2014 at 13:38  
  • +0 – @IonicBizu I've updated my answer — Aug 19, 2014 at 14:24