Using the HOSTS File

What Does it Do?

What is the HOSTS file? It’s a simple file that your operating system relies on to override DNS settings. It’s a very limited, albeit functional, way of overriding a DNS server to tell your computer where to send a request.

Where is the HOSTS File Located?

The location of the HOSTS file varies between Unix based systems and Windows System.

  • Windows – <system drive>:\windows\system32\drivers\etc\hosts
  • Mac OSX – /etc/hosts
  • Gnu/Linux – /etc/hosts

Format of the HOSTS File

The file is formatted like this

# The localhost entry should be in every HOSTS file and is used
# to point back to yourself.

127.0.0.1 localhost

# My test server for the website

192.168.1.2 test.example.com  # tells the operating system to send requests for "test.example.com" to IP 192.168.1.2
192.168.1.4 test3.example.com # tells the operating system to send requests for "test3.example.com" to IP 192.168.1.4

A Practical Example

Sometimes, it’d be really nice to develop websites without needing to rely on http://localhost/{name-of-project}/ . Using virtual hosts and the HOSTS file, you can get stuff like http://{name-of-project}.dev/ which I personally prefer to develop on.

Let’s say that you’re going to work on the next version of Gnarly Web, and you want to develop it on www.gnarlyweb.com. You will need to tell your computer to send requests for gnarlyweb.com and www.gnarlyweb.com to your localhost, so let’s add that to the HOSTS file.

# The localhost entry should be in every HOSTS file and is used
# to point back to yourself.

127.0.0.1 localhost

# My test server for the website

192.168.1.2 test.example.com  # tells the operating system to send requests for "test.example.com" to IP 192.168.1.2
192.168.1.4 test3.example.com # tells the operating system to send requests for "test3.example.com" to IP 192.168.1.4


# the following line tells your operating system to send requests for "gnarlyweb.com" and 
# "www.gnarlyweb.com" to the localhost

127.0.0.1    gnarlyweb.com    www.gnarlyweb.com 

Now, save the file, and your computer is ready to send requests for gnarlyweb.com to itself. By itself, this isn’t super useful, but if you set up a server of some sort, you can tell that server what to do when it hears that request.

Conclusion

This has two main uses:

  1. Develop a site locally, without any base Request URI
  2. Testing a production site before the rest of the world can see it
facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Thanks for your thoughts!