Created: 2017.05.27
A client recently asked me to edit my hosts file, in order to access a staging site.
DNS is used to resolve that domain name to its mapped IP address.
This is done by the device querying its configured DNS Servers and asking that server what the IP address is for that particular domain name. The DNS server will then query other servers on the Internet that know the correct information for that domain name, and then return to the device the IP address. The device will then open a connection directly to the IP address and perform the desired operation.
sudo nano /private/etc/hosts
12.34.5.678 domainname.com
After adding the mapping to my hosts
file, I was able to connect to http://domain.com, as if it was the live site, as well as access http://domain.com/cpanel.
... on most operating system the default configuration is that any mappings contained in the Hosts file overrides any information that would be retrieved from a DNS server.
In fact, if there is a mapping for a domain name in a hosts file, then your computer will not even bother querying the DNS servers that are authoritative for that domain, but instead read the IP address directly from the HOSTS file.
There is no need to reboot or enter another command to start using the entries in the HOSTS file.
But why not just connect directly to the IP address, 12.34.5.678
? What was the benefit of mapping this to the domain name? Was it just for vanity's sake?
The answer is no - the site was probably on shared hosting:
When you visit a site using its actual name, like "somerandomservice.com", the IP address is used to locate the server, and then the name you're asking for is also passed along. You can think of that request as being something along the lines of "Hello 72.3.249.232, I'd like to view somerandomservice.com, please". Without the domain name, the request is more like "Hello 72.3.249.232, show me your default site, please". On servers that host only one site, the results may be the same; on others, though, they're likely quite different.
(Source: Why doesn't accessing a site by its IP address work?)
- it allows you test a server or hosting environment, to make sure that it operates correctly, when people (and their applications) reference it as the true web server domain name, www.mydomain.com - before the domain is publicly mapped to the website
- you can test DNS changes and the SSL configuration before making a website live
- you can use the same links/bookmarks in development, issue tracking and testing of the newly live site
- avoid the usual WordPress migration hassles
(Source: Using an /etc/hosts file for custom domains during development)
- when a site is already live, and you need to compare a development server with the live site, perhaps when developing a new feature
- when you need to test file downloads - as any linked remote resources you wish to download will be unavailable, due to a mismatch between the request URL and DNS.