Foolproof Multi-environment Config

Problem

Your multi-environment config isn’t working properly, because the domain names you are using are too similar to each other.

Solution

Put this at the top of your public/index.php file:

switch (strtolower($_SERVER['SERVER_NAME'])) {
    case "local.domainname.com":
        define('CRAFT_ENVIRONMENT', 'LOCAL');
        break;
    case "staging.domainname.com":
        define('CRAFT_ENVIRONMENT', 'STAGING');
        break;
    default:   // Covers "www" and non-"www"
        define('CRAFT_ENVIRONMENT', 'PRODUCTION');
        break;
}

Then, use something like this in your config/general.php and config/db.php files:

return array(
    '*' => array(),
    'LOCAL' => array(),
    'STAGING' => array(),
    'PRODUCTION' => array(),
);

Discussion

This is an expansion on a few techniques, some of which are covered in the official Craft documentation on multi-environment configs.