November 2, 2024

What is the Hosts File?

The hosts file is a simple text file that allows you to map hostnames to IP addresses directly on your computer. It acts as a local DNS (Domain Name System) resolver, giving you control over how domain names are translated to IP addresses.

Key Purposes of the Hosts File

  • Block Websites: Redirect unwanted domains to localhost (127.0.0.1)
  • Override DNS Resolutions: Specify custom IP mappings
  • Local Development and Website Migrations: Point domain names to local development servers. It can also be used to temporarily point the website to be migrated to the new server IP pre-migration before making the changes go live
  • Improve Security: Block ads or malicious websites

Editing the Hosts File

Editing the hosts File in Linux is simple. It is located in /etc and can be directly opened through the Terminal. So use nano or vi or any of your favorite text editors. This example uses nano.

Important: Before changing the hosts file, as with most system related tasks, it is better to first backup the original. You can do that with the cp command:


sudo cp /etc/hosts /etc/hosts.bak
backup the hosts file before editing it

This will copy the contents of the original hosts file into a new file named hosts.bak (backup). Next, edit the original file using nano.


sudo nano /etc/hosts

opening hosts file in linux

The hosts file follows this format:

IP_ADDRESS   hostname   [optional_aliases]

default hosts file in linux

So, first add the IP address followed by the hostname or domain to which it would point to. 

adding a hosts entries in the hosts file in linux

Then save and exit. (In nano: Press Ctrl+O,  then Enter and for vi it would be :wq).

use ctrl-o in nano to write out changes

writing changes to the hosts file

You can verify these host file changes by pinging the domain or opening it in the browser. It should be served over the added IP address from the hosts file. 

To roll back the changes, add a # in front of the entries in the file.

commenting out changes in hosts file

Important Considerations

  • Changes take effect immediately
  • Requires root/sudo privileges
  • Modifications can impact system networking
  • Be careful when editing to avoid breaking system resolving

Best Practices

  • Always backup the original hosts file
  • Use comments to explain your modifications
  • Only make changes you fully understand

All done.

By admin

Related Post

Leave a Reply

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