What is /etc/hosts?

/etc/hosts is a text file on a computer that maps hostnames to IP addresses. It is used for static name resolution, which is not updated automatically like the Domain Name System (DNS) records.

/etc/hosts are usually the first file checked when resolving a domain name, so it can be used to block websites or redirect users to different websites. The default /etc/hosts look like below:

What is the /etc/hosts file in Linux General Articles
Default /etc/hosts file

Adding New Entry in /etc/hosts

You can also use /etc/hosts to resolve domain names that are not in the global DNS, such as local development servers or intranet servers. This can be done by adding entries for those servers in /etc/hosts with their corresponding IP addresses. For example:

What is the /etc/hosts file in Linux General Articles
Local domain binding with /etc/hosts
  • Here demo.example.com is mapped to 192.168.1.210 IP address
  • local.example.com is mapped with 127.0.0.1 (localhost).

Blocking Website with /etc/hosts

We can also use this file to prevent access to any domain. That can be helpful for parents to control website access to their loved ones. For example, If someone wants to block all traffic to facebook.com, they can add an entry in /etc/hosts that points facebook.com to 127.0.0.1, which is the loopback address and will not resolve to any actual website.

What is the /etc/hosts file in Linux General Articles
Blocking a domain access with /etc/hosts

/etc/hosts is a powerful tool that can be used for various purposes, and it is important to understand how it works to use it effectively.