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
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
The hosts file follows this format:
IP_ADDRESS hostname [optional_aliases]
So, first add the IP address followed by the hostname or domain to which it would point to.
Then save and exit. (In nano: Press Ctrl+O, then Enter and for vi it would be :wq).
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.
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.