Since the hosts file is editable, it can be used to prevent the browser from viewing unwanted IP addresses, and it can also be used to redirect the browser to a different IP address, such as that on your local computer or a remote server. For example, you can edit the hosts file on a mac to block malicious or inappropriate websites from being viewed in a browser. This I haven’t needed to do, but here’s how you can do it if you’re interested…
Open up the hosts file by going to: Applications -> Utilities -> Terminal
Type the following in Terminal:
sudo nano /etc/hosts
When prompted, enter in your system password.
Cursor down to the first blank line after localhost, then type in:
…followed by the domain of the site which you want to block (e.g., facebook.com).
What this does is force the domain of the website to resolve to your local machine, resulting in a browser error since it won’t be able to connect to the website.
Anyway… this is something I don’t do, but some of you out there may have a need to limit or monitor access to facebook, gambling sites, pron, etc… This can be helpful for preventing employees, children, etc… from visiting inappropriate sites.
To add a private hostname to the hosts file:
When I edit the hosts file, it’s typically to test a website that I’ve migrated from one server to another. I have four separate servers that I use for hosting, so occasionally I’ll shuffle sites around as their needs change. This is usually when a site outgrows the limits of shared hosting and needs to move to a VPS.
Once I’ve re-established the site’s account on the new server, I then edit my hosts file so that I can resolve the domain to its destination home. This allows me to fully test the copied site – making sure that the migration was a success, and that all the systems are in place and functioning properly.
Open up Terminal (Applications -> Utilities -> Terminal) and type in:
sudo nano /private/etc/hosts
Enter your password when prompted.
Cursor down and add the ip address of the destination server, followed by the domain name. Once you’re finished:
- Hit CTRL+O to save
- Press enter
- Hit CTRL+X to exit
Once this is done you’ll need to clear your DNS cache by typing in:
Now the copied site can be accessed via its domain name through a web browser.
Once the site is ready to go live, just re-open Terminal, delete the private hostnames, save using the steps outlined above, then flush the DNS cache again.
Hopefully this tutorial helps some of you out there. 🙂