How to use vhosts in Wordpress development

Wordpress development has some pitfalls, one of them being that it stores the domain in the database to reference all inner links. So if you develop locally, you have to replace all instances of localhost in the database before you upload to production. Lame. 

What follows is a little trick I use lately, nothing new I guess, but it might help your workflow. The idea is to create a virtual host locally with the same name of the production domain. Since local and production hosts will share the same name, you don’t have to worry about replacing strings in the database when you sync the code/database. Enough talking, here’s the method.

  1. Edit /etc/hosts and add a new entry for the new development site, named after the production domain:
    127.0.0.1 www.example.com
  2. Create a vhosts folder inside apache folder (if you’re using MAMP, this is typically /Applications/MAMP/conf/apache).
  3. Add a .conf file inside the vhosts folder, named after the production domain.  In our example this will be www.example.com.conf
  4. Content of this file will be the definition of the virtual host, name and path to local files:
    <virtualhost *:80>
        ServerName www.example.com
        DocumentRoot "/your/local/path/www.example.com/"
    </virtualhost>

    Note the use of www.example.com as ServerName.
  5. Change apache’s httpd.conf to automatically include all configuration files from the vhosts folder (add this at the very bottom):
    NameVirtualHost *:80
    Include /Applications/MAMP/conf/apache/vhosts/*.conf

Now, the idea is that you are telling your system that www.example.com resides in the 127.0.0.1 IP so you wouldn’t reach the production site. When you need to work locally, you use the line of the /etc/hosts to cheat your computer, start apache and check your code changes at www.example.com (it will show you the local environment). When you need to visit the live domain you comment that line, point your browser to www.example.com and you will reach the production site. 

You will probably need to add a fork in Wordpress config.php file to handle different user/pwd combo at development or production levels, something like:

define('DB_NAME', 'whatever_your_db_name_is');
if($_SERVER['SERVER_ADDR'] == '127.0.0.1') { // development
    define('DB_USER', 'development_db_username');
    define('DB_PASSWORD', 'development_db_password');
}
else { // production
    define('DB_USER', 'production_db_username');
    define('DB_PASSWORD', 'production_db_password');
}

User here does not refer to the Wordpress user but the user connecting to the MySQL.