Forward requests to another host with iptables

Like the cool kids in the block, I too am using Vagrant in my web development workflow. Everything is fine until I need to test the sites with real mobile browsers. Since the sites I’m working on are hosted inside a virtual machine, it’s not accessible from outside of the host machine.

Here’s how we can solve this using iptables. Let’s assume that the host machine’s IP is 192.168.1.2 and the guest/virtual machine’s IP is 10.86.73.80. These commands are to be run in the host machine as root:

iptables -F
iptables -t nat -F
iptables -X
iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 10.86.73.80:80
iptables -A FORWARD -d 10.86.73.80 -p tcp --dport 80 -j ACCEPT
iptables -t nat -A POSTROUTING -j MASQUERADE

Now, add the site’s domain to your rooted phone’s /etc/hosts file or your router’s configs:

192.168.1.2  mylocalsite.dev

You can save the rules above permanently with:

iptables-save > /etc/iptables/iptables.rules
Forward requests to another host with iptables

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.