With various tools helping with testing and development, the hosts file is often forgotten. Its main task is to translate a user friendly domain names into not-so friendly IP addresses. The gist is that the operating system checks it before querying DNS servers.
On Windows machines it’s located at %SystemRoot%\system32\drivers\etc\hosts and /etc/hosts on Linux. To edit it you will need to launch your favorite text editor as an Administrator or use sudo.
The syntax is simple: first you type the IP address and then list of domain names that you want to point to it. Multiple domains per line are allowed as long as they are separated by a space or tab. To comment out a line use a # character.
220.127.116.11 orderofcode.com www.orderofcode.com
192.168.2.23 orderofcode.local www.orderofcode.local
127.0.0.1 reddit.com #Reddit self blocking ;)
Changes are immediate, but browsers may cache DNS entries and might need a restart. To verify that hosts redirection works ping the redirected domain name. You should see that IP from hosts file is used. Don’t use nslookup though, as it will query DNS server and return the original address.
Examples of use are just like Emperor Palpatine power: (almost) unlimited.
- Redirection of a name to a locally hosted development version of a website.
- Reaching to a certain node behind load balancer while preserving the original URL.
- Testing server configuration without making any changes to DNS entries
- Blocking unwanted traffic to a remote server.
- Blocking Facebook or Reddit if you spend too much time there.
- Pulling off some amazing pranks.