Automatic /etc/hosts on Apples’ OS X

Setting up directory based hosts file (aka Dynamic DNS)

Setting up new entries in /etc/hosts is a pain. Apache has mod_vhost_alias, but without some type of wildcard or dynamic DNS support, you still have to setup entries in hosts.

I want my hosts file to automagicly get updated when I create a new directory.

With a little help from Apple’s launched this script can automate your /etc/hosts file.

Step 1, Backup your original hosts file

First, backup your /etc/hosts file to /etc/

Step 2, The dynamic DNS script

In your home directory create a new PHP script called dynamic_hosts.php.

[pastacode lang=”php” user=”jstormes” repos=”DynamicHosts” path_id=”dynamic_hosts.php” revision=”master” highlight=”” lines=”” provider=”github”/]

Get code from GitHub

The above code will scan the path passed on the command line for new directories.  If new directories are found, it will append the directory/sub-directory into the /etc/hosts file as

Setting the code to execute

Copy the code into the /bin directory:

Set the script to be executable:

Step 3, The directory watcher

Create the file DynamicHosts.plist in your home directory. 

[pastacode lang=”markup” user=”jstormes” repos=”DynamicHosts” path_id=”DynamicHosts.plist” revision=”master” highlight=”” lines=”” provider=”github”/]

Get code from GitHub 

Be sure to change the two paths (/usr/local/zend/apache2/htdocs/) in the above file to match the path to your web root.  Be sure to include the trailing “/”.

Copy the file to /Library/LaunchDaemons/.

Step 4, Change the permissions and start the LaunchAgent

To stop monitoring the directory:


To set the setup create a directory and sub-directory in your webroot.  If the script is running correctly you will see a new entry in /etc/hosts that will match your directories.

Next Time:

Setting up mod_vhost_alias in Apache to work with the above setup.

No Responses

Leave a Reply