Showing Correct WordPress Domain on Each Server

Posted (Updated ) in PHP

If you’re running WordPress on multiple servers, chances are you’ve come across an issue where once you’ve copied WordPress to the new domain, none of your scripts, styles or images are loading. One of the most common occurrences of this happening is running an installation on your local machine (localhost) and allowing people from an internet or network IP to view it. If you dig a little further by viewing page source you’ll notice the issue is caused by WordPress using your old domain (or localhost) for loading – resulting in extreme load on a single server or worse; a HTTP 404 error.

There are several ways to fix this issue.

1. Simply go to the admin for each installation and manually change your WordPress Admin – Settings – General – “WordPress Address (URL)” and “Blog Address (URL)” settings for each server. Not only is this a pain but it also stops you from being able to do complete database dumps from one domains DB to the other – as the setting would be overridden each time.

2. If running only on localhost and allowing people to view externally, you can edit your hosts file, pointing your external domain towards then loading your site using your domain instead of localhost. Problem with this is, every network IP wanting to view the site will also need to do this, replacing with your network IP. Bad solution.

It turns out WordPress offers an easy way of overriding the admin settings by placing a PHP constant in your wp-config.php file (located in your blog address folder – by default this is just your WordPress installation directory). We can combine this trick with PHP’s $_SERVER variable to automatically define the domain your installation is currently on – resulting in a WordPress installation that will work anywhere. Simply add the following script to your wp-config.php file:

define('WP_HOME',    'http://'.$_SERVER['HTTP_HOST']);
define('WP_SITEURL', 'http://'.$_SERVER['HTTP_HOST']);