Using a hosts file

One of our handy development trick is the judicious use of the hosts file on our local computer. This file controls access to various domains by the use of specifying alternative IP addresses. Usually, this file has very few entries, with the most common being this one:

127.0.0.1 localhost

Look familiar? This is how your computer gets a local, or home, IP address. Typing in that IP will always point back to your local computer.

The way you can use this to your advantage is to point any domain out there back to your computer. There are plenty of posts out there explaining how to set up a local development copy of your site. This is something we also do a lot of. We use the hosts file to specify some (basically fake) domain names so we can set up different install to test a lot of different things. For example, my local machine has an AMD64 processor, so we set up a local domain called amd64.local in my hosts file. At a glance, I know I’m working locally, and I have the benefit of working on something other than just “localhost”.

So far, everything has been pretty straightforward. Here comes the fun part.

You can actually specify a real live domain in the hosts file to point to your local machine.

127.0.0.1 yourdomain.com

on a new line.

The only person this affects is anyone using your computer, and you can quickly change this at any time. Why would you do this? (Here’s the juicy bit). In multisite, to run a development version, it can be really tedious to make changes and fix the database every single time, as the domain is listed in numerous tables.

Mostly, you can set up a copy of your live network on your local machine, not have to change any files (maybe wp-config to get to the local db) and just change the hosts file so you can see your local copy. As if it were live.

This way, you can test an upgrade locally, or new plugins, or extensive changes, before you go breaking things on a live site. You’ll be able to figure out fixes without the added pressure of a site being down.

When you wish to view the live site again, just edit the hosts file again and remove the line you added. Yes, you do have to flip back and forth, but it is a lot less work than the alternative.

In Windows 7, the file is located at C:\Windows\system32\drivers\etc\ .
On a Mac, the file is in /etc/hosts.

Comments

  1. I use this trick with my local dev installs. I’ve set up mirror copies of some of my live sites that I’m building/rebuilding, and just use the first part of the real domain name with a .dev at the end, i.e. domain1.dev, domain2.dev, etc. This way I can build everything locally and push it to the live server when it’s finished.

    I’ve also gotten Multisite working with subdomains locally by adding each of the subdomains to the hosts file (sub.domain1.dev) – works perfect! :)