Using your hosts file to preview a site before changing the DNS

Even if your web host does offer a method of previewing a site before you’ve changed the DNS, it’s usually more trouble than it’s worth, particularly if the method is a proxy and your site code includes hardcoded paths or URLs. (I’m looking at you, GoDaddy, with your PreviewMyWebSiteNow).

As an alternate, you can configure your hosts file. A hosts file is a text file on your computer that maps domains to server IP addresses, just like the Domain Name Server (aka DNS) does, except locally. Here’s how:

  1. Obtain your site’s IP address. Most hosting control panels (like cPanel or Plesk) have this information on the main dashboard.
  2. Find your hosts file. This depends on what platform you’re using. For Mac it will be /private/etc/hosts. For Windows, C:\\Windows\System32\Drivers\etc\hosts. For Linux, /etc/hosts.
  3. Create a backup copy of your hosts file. If living dangerously, skip this step.
  4. Open hosts for editing. If you get a permissions error, try it as sudo.
  5. Add a line to the bottom of the file, containing the server IP address and domain, separated with a space, like so:
    127.0.0.1 facebook.com

    [Note: The example above effectively blocks Facebook, which is why you never let your nerd friend borrow your laptop unsupervised.]

  6. Save the file and test. If the domain isn’t resolving to the new site, try dumping your DNS cache and restart your browser.

Caveats

  • This will only remap the domain on your local machine. The domain mapping will be unchanged for anyone else (such as a client).
  • Remember to remove this entry from your hosts file when you change the DNS for real.