What is the hosts file?
The hosts file is an operating system file which maps hostnames to IP addresses. It is a plain-text file with the name ‘hosts’ with no file extension.
Why we would we want to edit the hosts file?
Normally hostnames are mapped to IP address with DNS, however we can override this for specific addresses by adding entries to the hosts file.
This could be useful for developing websites when:
- Mapping private domains locally
- Hosting has already been set up, but the DNS update has not propagated.
The Format of Hosts file entries
Each hosts file entry is a line of text within the hosts file. Each line consists of an IP address in the first text field followed by one or more hostnames. Separate each field with space (single or multiple spaces can be used) or tab characters.
We can include comment lines by preceding the comment with a hash character (#) at the beginning of the line.
Blank lines can also be included and will be ignored.
#----------------------------------------------- # My Server 192.168.0.2 myserver.local 192.168.0.3 myotherserver.local myotherserveralias.local #-----------------------------------------------
How to edit the hosts file on a Mac
To edit the hosts file we need to start a text editor with admin rights. One way to do this is start the text editor via a terminal window. If you do not have a shortcut to the terminal in your toolbar, you will find it at Application -> Utilities -> Terminal.app or type “terminal” into search
Enter the command: sudo open -t /etc/hosts and press return.
You will then be prompted to input your password.
The hosts file will then open in your text editor for editing.