OS X Port Forwarding for Development on a Vagrant Guest

Temporarily repoint mydomain.com to localhost during development. This means you can develop mydomain.com, and when deploying to production you can be confident there are no ‘localhost’ references in your source.

There are three elements to this:

  1. Edit your hosts file:
    sudo vi /etc/hosts
    Add the line:
    192.168.50.1 mydomain.com
    (the IP address is the IP of the guest VM)
  2. Forward port 8080 on the host to the guest in your Vagrantfile:
    config.vm.network :forwarded_port, guest: 80, host: 8080, auto_correct: true
  3. Update iptables to forward requests to localhost:8080 to guest:

    sudo ipfw add 100 fwd 127.0.0.1,8080 tcp from any to any 80 in

Use sudo ipfw flush to remove the mapping.

Wrap it up in a function for your .functions file:

# $1 Domain
# $2 IP Address
forward(){
	echo "$2 $1" | sudo tee -a /etc/hosts
	sudo ipfw add 100 fwd 127.0.0.1,8080 tcp from any to any 80 in
	dscacheutil -flushcache
}

# $1 Domain
remove_forward(){
	sudo sed -i "" "/$1/d" /etc/hosts
	dscacheutil -flushcache
	sudo ipfw flush
}