How to edit the hosts file in Mac OS X – Leopard

I recently had a situation where, after a failed attempt at configuring an AMPPS development environment on my macbook pro, I suddenly was unable to visit one of my websites — the http address would not resolve. I could reach it by FTP, just not by any browser. What was fishy was that I could reach the website from other computers on the SAME network, just not my laptop. The website address was the only one that was effected on the laptop, I could visit other sites fine. The website address in question was the same site I had created a copy of in my AMPPS development environment. A support rep pointed me in the direction of editing my system’s hosts file, but didn’t know how to do it on a mac. Thank you Giannis in Thessaloniki, Greece, for posting the solution. Originally posted on the blog “Decoding the Web.” Original link: http://decoding.wordpress.com/2009/04/06/how-to-edit-the-hosts-file-in-mac-os-x-leopard/ 
 

Introduction

The hosts file is a text file that maps hostnames to IP addresses.
Upon typing a url address on the browser, the system is checking if there is a relevant entry on the hosts file and gets the corresponding IP address, else it resolves the IP via the active connection’s DNS servers.

The hosts file can be edited to block certain hostnames (like ad-serving/malicious hosts), or used for web development purposes, i.e. to redirect domains to local addresses.

Editing the hosts file

Editing the hosts file in Mac OS X – Leopard, is a pretty easy task, especially if you are familiar with the terminal.

Step 1 – Open the Terminal.app

Either by start typing Terminal on the Spotlight, or by going into Applications -> Utilities -> Terminal.

Step 2 – Open the hosts file

Open the hosts by typing on the Terminal that you have just opened:

$ sudo nano /private/etc/hosts

Type your user password when prompted.

Step 3 – Edit the hosts file

The hosts file contains some comments (lines starting with the # symbol), as well as some default hostname mappings (e.g. 127.0.0.1 – localhost).
Simply append your new mappings underneath the default ones. Or edit one of the default values if you know what you are doing!
You can navigate the file using the arrow keys.

Step 4 – Save the hosts file

When done editing the hosts file, press control-o to save the file.
Press enter on the filename prompt, and control-x to exit the editor.

Step 5 – Flush the DNS cache

On Leopard you can issue a simple Terminal command to flush the DNS cache, and have your host file changes to take immediate effect:

$ dscacheutil -flushcache

You can now test your new mapping on the browser!