in Web Development

Organising Your Hosts File

If you're freelancer or work for a large company you could find yourself with a large and sometimes out of control /etc/hosts file. I can have about 50 sites on there at a time, some are active and other are not. I try to split up the sites on a per project basis with a commented title such as:


###############################
# Project 1
###############################
xxx.xx.xx.xxx site-1.com
xxx.xx.xx.xxx site-2.com
xxx.xx.xx.xxx site-3.com

###############################
# Project 2
###############################
xxx.xx.xx.xxx site-1-1.com
xxx.xx.xx.xxx site-1-2.com
xxx.xx.xx.xxx site-1-3.com

This works ok but can slowly get out of control and I wanted a better way of managing these site. The end solution of what I want is to split up the projects into different host files and then include all of these files inside the /etc/hosts file.


@include project-1.conf
@include project-2.conf

After doing some research I couldn't find a nice way of including the hosts from within the hosts file, but then thought I can write a script to build the etc/hosts file from the different project config files. ### Create A Hosts Directory

First create a folder in the /etc/ folder for the hosts.


> sudo mkdir /etc/hosts.d

Create Project Host Files

Now create a conf file inside this folder for each of your host projects.


> sudo nano /etc/hosts.d/project-1.conf
> sudo nano /etc/hosts.d/project-2.conf

Create Script To Build Host File

First create the file inside the hosts.d folder.


> sudo nano build-hosts.sh

Inside this file we want to concatenate all the hosts conf files into the hosts file.


cat /etc/hosts.d/*.conf > /etc/hosts

Now run the build host script.


> sh /etc/hosts.d/build-hosts.sh

This will create the /etc/hosts file with all the configs in the hosts folder. Therefore whenever you want to update your host file you can run this script to re-build it from the configs for you.

Upgrade to access all content on Paulund

Members unlock all tutorials and snippets

Access to all downloadable content

Access to code examples before others

Sign Up Now

Already a member? Login here

Subscribe To The Weekly Newsletter

Get weekly updates to your email