Hosting two webservers on port 80

Posted on Mon 20 June 2022 in Software

I run a couple of servers with PiHole on them for local DNS and I wanted to host another webserver on one of the boxes running PiHole. You can't assign two services to the same port on the same interface, and I only had one physical interface.

How I accomplished this, without disabling the built in PiHole webserver is to run my other webserver on port 800 (any other port will do though). I then added a second IP (static) to my existing interface. I edited my /etc/networks/interfaces.d/eth0 file to look like:

auto eth0
allow-hotplug eth0
iface eth0 inet dhcp

auto eth0:0
iface eth0:0 inet static
  address 192.168.1.101
  netmask 255.255.255.0

I then added an iptables rule to route to my alternative webserver based on destination IP. 192.168.1.20 is the DHCP assigned IP address for the same box.

sudo iptables -t nat -A PREROUTING -p tcp --dport 80 --dst 192.168.1.20 -j DNAT --to-destination 192.168.1.20:800

From that point on, as long as I'm using the right IP address, I can access whichever webserver I want and get the content I expect.

I also added a local DNS record in my PiHoles with the IP, so things had a nice name to access them.