What is hosts file and how to use it to override DNS?

Introduction

The hosts file is a plain text file on a computer located in one of the system folders. This file has the details to map hostnames (e.g., domain names) to IP addresses. It acts as a local DNS (Domain Name System) resolver and allows you to override or customize the DNS resolution for specific domains on your machine. This feature can be particularly useful during website migrations to a new hosting server, when you wish to preview your website on a different server, even before propagating DNS to the new server.

Utilizing the Hosts File: Overriding DNS in Simple Steps

Step 1

To start with, locate the hosts file on your operating system:

Windows: The hosts file is located at:

C:\Windows\System32\drivers\etc\hosts.
Location of hosts file on windows

macOS: The hosts file is located at:

/etc/hosts
Location of hosts file on macOS

Linux: The hosts file is located at:

/etc/hosts
Location of hosts file on Linux

Step 2

Open the hosts file using a text editor with administrative privileges.

NOTE: On Windows, you may need to run the text editor as an administrator.

Step 3

Add an entry to the hosts file in the following format:

<IP_Address> <Hostname>

Replace <IP_address> with the IP address you want to map the hostname to, and <hostname> with the domain or hostname you want to override. For example:

127.0.0.1 example.com

In this case, we are mapping the hostname example.com to the local loopback address 127.0.0.1.

Hosts file on Windows:

Hosts File on macOS:

Hosts file on macOS

Hosts File on Linux:

Hosts file on Linux

Step 4

Save the hosts file.

Step 5

Flush the DNS cache to ensure the changes take effect:

Windows: Open the command prompt as an administrator and run the command:

ipconfig /flushdns

macOS: Open the Terminal and run the command:

sudo killall -HUP mDNSResponder

Linux: Open the Terminal and run the command:

sudo systemctl restart network-manager

Once the hosts file is modified, your operating system will employ the IP address specified in the file to associate with the respective hostname. This allows you to override the DNS resolution and point a domain to a different IP address on your local machine.

It is essential to understand that alterations made to the hosts file solely impact the local machine on which the file is modified. Other devices on the network will not be affected by these changes. Additionally, you may need to remove or comment out the entries in the hosts file to revert to the default DNS resolution for those domains.

Reference


Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.