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.
1 |
/var/htdocs/develop.dev/someproject --> http://someproject.develop.dev |
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/hosts.org:
1 |
sudo cp -p /etc/hosts /etc/hosts.org |
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”/]
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 127.0.0.1 sub-directory.directory.
Setting the code to execute
Copy the code into the /bin directory:
1 |
sudo cp dynamic_hosts.php /bin |
Set the script to be executable:
1 |
sudo chmod a+x /bin/dynamic_hosts.php |
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”/]
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/.
1 |
sudo cp DynamicHosts.plist /Library/LaunchDaemons/ |
Step 4, Change the permissions and start the LaunchAgent
1 2 3 |
sudo chown root:wheel /Library/LaunchDaemons/DynamicHosts.plist sudo chmod 644 /Library/LaunchDaemons/DynamicHosts.plist sudo launchctl load -w /Library/LaunchDaemons/DynamicHosts.plist |
To stop monitoring the directory:
1 |
sudo launchctl unload /Library/LaunchDaemons/DynamicHosts.plist |
Testing:
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.