Previewing a site on a new server by changing your hosts file

So, you're moving a succesful website to a new server. Or, you've created a shiny new site that your client loves. It's running on a test server somewhere, but you want to make sure it will run smoothly on the client's domain.

Well, running the site through a url like my.testserver.myhostingcompany.com/~youraccount could conflict with your site's configuration. You want to test it throug www.example.com. Hosts file to the rescue!

So, how does this work?

Your browser will use the entries in your hosts file before it looks up the DNS information for your domain. In other words, if you state in your hostsfile taht www.example.com is located at IP 123.456.78.90, then that is exactly where it will look for that site.

Editing your host file

On a Mac, your hosts file is typically located at /etc/hosts. You need to open it using administrator rights. The easiest way is to use the terminal for this.

sudo vi /etc/hosts

The contents will look typically something like

127.0.0.1 laravel.dev
127.0.0.1 mytestsite.dev

At the bottom of the file, add the IP listing for your website. Scroll down to the bottom of the file, type i to be able to insert new text and add the proper IP address and server name. To be on the safe side, enter both with and without www.

123.456.78.90 example.com
123.456.78.90 www.example.com

Now, save the file. First, press Esc to exit write mode, then :wq to save the file. Now close all browser instances and flush your DNS cache. On a Mac that's

dscacheutil -flushcache

That's it! From now on, when you open a browser and type www.example.com, you will look at the site located at 123.456.78.90.