How to forward a domain to a Vagrant VM with Apache on OSX

January 27th, 2015

Warning: This post is 9 years old. Some of this information may be out of date.

I do a lot of my development work using Virtual Machines and Vagrant. This provides an easy way for me to get a working environment up and running locally on the many projects I work on daily. However, one of the problems with this is that these VMs aren't accessible externally. This can be a problem when you need to show your work or use a third party service that needs access to the site.

I've solved this problem by using a dynamic domain name service together with Apache's mod_proxy. Essentially the domain name points to my Macbook and Apache forwards the traffic to the Vagrant VM.

Here's how it is done. Imagine I have a dynamic domain name of andrew.dyn.dns.com pointing at my macbook, and a website devsite.andrew.dyn.dns.com running on the Vagrant VM (with the IP address 192.168.56.10). Apache2 is installed on the Macbook (by default).

First, Edit /etc/apache2/http.conf and uncomment the following line:

    LoadModule proxy_module libexec/apache2/mod_proxy.so

Add the following to /etc/apache2/extra/httpd-vhosts.conf:

    <VirtualHost *:80>
      ServerName devsite.andrew.dyn.dns.com
    
      ProxyPreserveHost On
      ProxyPass / http://192.168.56.10/
      ProxyPassReverse / http://192.168.56.10/
    
    </VirtualHost>

Note: I had issues with Firefox timing out with a Proxy Error until I added the ProxyPreserveHost On line to the VirtualHost.

Finally, restart Apache:

    sudo apachectl restart

Test it by visiting http://devsite.andrew.dyn.dns.com and you should see your website.