What is the Hosts File?
The hosts file is a plain text file used by your operating system to map hostnames to IP addresses. It’s like an address book for your computer that tells it where to find websites on the internet.
Why edit the Hosts File?
- Preview changes to a website before it goes live.
- Test a website on a new server without changing the DNS.
- Block access to certain websites for security reasons.
Edit the Hosts File
1. Open the Hosts File
The location of the hosts file varies depending on your operating system:
- Windows:
C:\Windows\System32\drivers\etc\hosts - Mac and Linux:
/etc/hosts
2. Backup the Hosts File
Before making any changes, it’s a good idea to create a backup of the hosts file.
- Windows: Copy the file to another location.
- Mac and Linux: Use the terminal command:
sudo cp /etc/hosts /etc/hosts.backup
3. Edit the Hosts File
Windows
- Open Notepad as an administrator:
- Search for
Notepadin the Start menu. - Right-click and select
Run as administrator.
- In Notepad, go to
File>Openand navigate toC:\Windows\System32\drivers\etc\hosts.
- Select
All Filesin the file type dropdown to see the hosts file.
- Add your new entries at the end of the file:
127.0.0.1 example.com
192.168.1.1 test.example.com
127.0.0.1is the IP address for your local machine.- Replace
example.comandtest.example.comwith the domains you are testing.
Mac and Linux
- Open the Terminal.
- Use the
nanotext editor to open the hosts file with administrative privileges:
sudo nano /etc/hosts
- Enter your password if prompted.
- Add your new entries at the end of the file:
127.0.0.1 example.com
192.168.1.1 test.example.com
- Press
CTRL + X, thenY, andEnterto save and exit.
4. Flush the DNS Cache
After editing the hosts file, you may need to flush your DNS cache to apply the changes.
Windows
- Open Command Prompt as an administrator:
- Search for
cmdin the Start menu. - Right-click and select
Run as administrator.
- Type the following command and press Enter:
ipconfig /flushdns
Mac
- Open Terminal.
- Type the following command and press Enter:
sudo killall -HUP mDNSResponder
Linux
- Open Terminal.
- Depending on your distribution, type one of the following commands:
sudo systemctl restart network-manager
or
sudo /etc/init.d/nscd restart
Tips and Troubleshooting
- Permissions: Ensure you have administrative or root permissions to edit the hosts file.
- Syntax: Double-check your entries for correct IP addresses and domain names.
- Revert Changes: If something goes wrong, you can restore your backup hosts file.
Editing the hosts file is a simple yet powerful tool for web developers and IT professionals. With this guide, you should be able to preview websites or make local changes easily and safely.