Giter Club home page Giter Club logo

wordpress-multi-env-config's Introduction

Studio 24 WordPress Multi-Environment Config

This repository contains Studio 24's standard config setup for WordPress, which loads different config based on current environment. This allows you to have different site configuration (e.g. debug mode) for different environments (e.g. production and staging).

Credit is due to FocusLabs EE Master Config who gave me the inspiration for the organisation of the config files.

Please note the current version is v2, if you need to use the older v1 version please see the v1 release.

Contributing

Strata is an Open Source project. Find out more about how to contribute.

Security Issues

If you discover a security vulnerability within WordPress Multi-Environment Config, please follow our disclosure procedure.

How it works

The system detects what environment the current website is in and loads the relevant config file for that environment.

By default the environment is defined by the hostname, though you can also set this as an environment variable.

Config files are then loaded according to the current environment. There is support for loading a local config file for sensitive data, which is intended to not be committed to version control.

Config files

Up to three different config files are loaded:

  1. Default configuration (in wp-config.default.php, e.g. shared settings such as $table_prefix)
  2. Environment configuration (in wp-config.{ENVIRONMENT}.php, e.g. any setting specific to the environment such as database name or debug mode)
  3. Optional local settings (in wp-config.local.php, e.g. any sensitive settings you do not want to commit to version control, e.g. database password)

Environment values

By default, environment values are:

  • production (live website)
  • staging (test website for client review)
  • development (local development copy of the website)

You can add other environment values by adding these to the wp-config.env.php file.

Setting the environment

The current environment is detected in one of three ways:

Environment variable

You can set an environment variable called WP_ENV to set which environment the website uses in your webserver configuration.

This is commonly done via Apache in your virtual host declaration:

SetEnv WP_ENV production

If you don't use Apache consult your webserver documentation.

Server hostname

The current environment can also be detected from matching the hostname with the domain setup in wp-config.env.php.

WP-CLI

If you're using WP-CLI you can specify your environment using an '.env' file.

You need to create a file called .env and simply write the current environment in this file as a string.

Example:

development

This file needs to be placed among the wp-config.*.php files (this applies if you keep these files in a sub-folder and the wp-config.php file in the web root).

It is recommended you do not add this file to version control.

The wp-config.env.php file

You need to edit the wp-config.env.php file to define some settings related to the current environment URL. This needs to be set regardless of which method is used to set the environment, since all methods set the WordPress URL via settings contained in this file.

This file contains a simple array, made up of:

environment names =>
    domain  => The domain name.
               This can also be an array of multiple domains.
               You can also use a wildcard * to indicate all sub-domains at a domain, which is useful when using
               WordPress Multisite. If you use wildcards, set the domain should to a single string, not an array.
    path    => If WordPress is installed to a sub-folder set it here.
    ssl     => Whether SSL should be used on this domain. If set, this also sets FORCE_SSL_ADMIN to true.

Example usage:

$env = [
    'production'  => [
        'domain' => 'domain.com',
        'path'   => '',
        'ssl'    => false,
    ],
    'staging'     => [
        'domain' => 'staging.domain.com',
        'path'   => '',
        'ssl'    => false,
    ],
    'development' => [
        'domain' => 'domain.local',
        'path'   => '',
        'ssl'    => false,
    ],
];

If you use localhost for your local test website, just set the development hostname case to localhost rather than domain.local.

Example usage when setting a sub-folder, and also serving the live site via SSL:

    'production'  => [
        'domain' => 'domain.com',
        'path'   => 'blog',
        'ssl'    => true,
    ],

Example usage for using more than one domain for an environment.

    'production'  => [
        'domain' => ['domain.com', 'domain2.com'],
        'path'   => '',
        'ssl'    => false,
    ],

Example usage when using a wildcard for WordPress multi-site.

    'production'  => [
        'domain' => '*.domain.com',
        'path'   => '',
        'ssl'    => false,
    ],

Installing

Please note this requires PHP5.4 or above. You should really be on PHP5.6 at a minimum!

  1. Download the required files via wordpress-multi-env-config.zip
  2. First make a backup of your existing wp-config.php file.
  3. Copy the following files from this repository to your WordPress installation:
wp-config.default.php
wp-config.env.php
wp-config.php
wp-config.load.php
  1. Set the correct environments you wish to support via the file wp-config.env.php, see the documentation above.
  2. Create one wp-config.{environment}.php file for each environment. You can use the sample files provided in this repository:
wp-config.development.php
wp-config.production.php
wp-config.staging.php
wp-config.local.php
  1. Review your backup wp-config.php file and copy config settings to either the default config file or the environment config files as appropriate. It is suggested to:
    • If the setting is the same across all environments, add to wp-config.default.php
    • If the setting is unique to one environment, add to wp-config.{environment}.php
    • If the setting is sensitive (e.g. database password) add to wp-config.local.php
  2. Remember to update the authentication unique keys and salts in wp-config.default.php
  3. If you use version control exclude wp-config.local.php, an example below for Git:
# .gitignore
wp-config.local.php

You should now be able to load up the website in each different environment and everything should work just fine! It should now be safe to delete your backup wp-config.php file.

Moving your config files outside of the document root

If you want to store your config files outside of the document root for additional security, this is very easy.

Simply move all the config files except for wp-config.php itself into another folder (which can be outside the doc root). Next amend the require path for wp-config.load.php in wp-config.php to point to the new location and everything will work just fine!

Example directory structure:

config/
       wp-config.default.php   (Config folder outside of doc root)
       wp-config.development.php
       wp-config.env.php
       wp-config.load.php
       wp-config.local.php
       wp-config.production.php
       wp-config.staging.php
web/
    wp-config.php              (Your website doc root, where WordPress is installed) 

Example wp-config.php

/** Load the Studio 24 WordPress Multi-Environment Config. */
require_once(ABSPATH . '../config/wp-config.load.php');

wordpress-multi-env-config's People

Contributors

amarcadet avatar dino-conceptable avatar github-actions[bot] avatar jerschneid avatar maries24 avatar newtlabs avatar simonrjones avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wordpress-multi-env-config's Issues

Use with W3 Total Cache

Just found your multi-environment config and am checking it out.

I use the W3 Total Cache plugin, and it modifies wp-config.php.

In my wp-config.php, I have the following at the very top:

define('COOKIE_DOMAIN', 'my.domain.com'); // Added by W3 Total Cache

/** Enable W3 Total Cache */
define('WP_CACHE', true); // Added by W3 Total Cache

/** Enable W3 Total Cache Edge Mode */
define('W3TC_EDGE_MODE', true); // Added by W3 Total Cache

I think that setting of COOKIE_DOMAIN by W3 is going to cause problems. Have you encountered this in your practice?

.gitignore rules

Hi,

Do I need to add any of these config files into .gitignore for security reasons? Or can they be safely hosted on production environments?

Thanks

Using XAMPP localhost

Hi, I'm trying to use the dev version of my site on localhost, with http://domain.local but I'm not sure how to connect it. The production version: http://domain.com and staging version: http://staging.domain.com share wp-admin, wp-includes and plugin folders, while the DBs and wp-content folders are different for each version.

For my local install I'm working on XAMPP and I would like to share the plugins and media folders for the three versions, though I don't know if what I need to configure for the development version, a.k.a. domain.local, is the wp-config.development.php or the wp-config.php in localhost?

Database error

Hi!
I found this via a T3N-article and tried to use it now.
Got problem "Error establishing a database connection" on local dev machine and on live system though DB-settings are correct.
Can´t find the error...

EDIT: It´s a multisite installation but I don´t think it matters?!

Can't use array for multisite across multiple environments

Hi, I'm updating an old version of the multi-env config to the latest version for a multisite. Before it worked fine but the newer one has issues.

Testing locally, the development environment doesn't work with other environments in front of it. Example:

$env = [
'production' => [
'domain' => ['example.com', 'sub.example.com'],
'path' => '',
'ssl' => true,
],
'staging' => [
'domain' => ['staging.example.com', 'stagingsub.example.com'],
'path' => '',
'ssl' => true,
],
'development' => [
'domain' => ['example.test', 'sub.example.test'],
'path' => '',
'ssl' => true,
],
];

Errors:

PHP Warning: strpos() expects parameter 1 to be string, array given in /sites/example.com/wp-config.load.php on line 77
PHP Warning: preg_quote() expects parameter 1 to be string, array given in /sites/example.com/wp-config.load.php on line 79
PHP Warning: trim() expects parameter 1 to be string, array given in /sites/example.com/wp-config.load.php on line 135
PHP Warning: trim() expects parameter 1 to be string, array given in /sites/example.com/wp-config.load.php on line 138
PHP Warning: strpos() expects parameter 1 to be string, array given in /sites/example.com/wp-config.load.php on line 77
PHP Warning: preg_quote() expects parameter 1 to be string, array given in /sites/example.com/wp-config.load.php on line 79
PHP Warning: trim() expects parameter 1 to be string, array given in /sites/example.com/wp-config.load.php on line 135
PHP Warning: trim() expects parameter 1 to be string, array given in /sites/example.com/wp-config.load.php on line 138

Can i use $env in theme

Hello,

Nice Plugin and it works beautiful.
I have a question. Is it possible to use $env in my theme?

greetings

Edit:
oh sorry, i have found it. There are constants like WP_ENV, WP_ENV_DOMAIN, WP_ENV_PATH and so on.

Wordpress in sub-directory not working without defining WP_HOME, WP_SITEURL

Hello,

I had some trouble getting wordpress to work in a subdirectory. Our company blog sits in a subdirectory /blog/. Database and everything is set, all worked fine until I installed this multi-env-config.

To fix I had to add . 'blog' to the end of the Define WordPress Site URLs in the wp-config.php

if (!defined('WP_SITEURL')) { define('WP_SITEURL', $protocol . rtrim($hostname, '/') . '/blog'); } if (!defined('WP_HOME')) { define('WP_HOME', $protocol . rtrim($hostname, '/') . '/blog'); }
Was this expected behavior?

New WP-cli issue

Hi, now that new features have been added to master I'm having issues when trying to activate something via wp-cli, I have also tried adding --env= to the command but no avail.

Errors:

PHP Notice:  Undefined variable: argv in /wp-config.load.php on line 23
PHP Warning:  Invalid argument supplied for foreach() in /wp-config.load.php on line 23
PHP Notice:  Undefined index: HTTP_HOST in /wp-config.load.php on line 42
PHP Fatal error:  Uncaught Exception: Cannot determine current environment via WP_ENV or hostname in /wp-config.load.php:46
Stack trace:
#0 /wp-config.load.php(122): s24_load_environment_config()
#1 phar:///usr/local/bin/wp/php/WP_CLI/Runner.php(964) : eval()'d code(14): require_once('/var/www/h...')
#2 phar:///usr/local/bin/wp/php/WP_CLI/Runner.php(964): eval()
#3 phar:///usr/local/bin/wp/php/WP_CLI/Runner.php(927): WP_CLI\Runner->load_wordpress()
#4 phar:///usr/local/bin/wp/php/WP_CLI/Bootstrap/LaunchRunner.php(23): WP_CLI\Runner->start()
#5 phar:///usr/local/bin/wp/php/bootstrap.php(75): WP_CLI\Bootstrap\LaunchRunner->process(Object(WP_CLI\Bootstrap\BootstrapState))
#6 phar:///usr/local/bin/wp/php/wp-cli.php(23): WP_CLI\bootstrap()
#7 phar:///usr/local/bin/wp/php/boot-phar.php(8): include('phar:///usr/loc...')
#8 /usr/local/bin/wp(4): include('phar:///usr/loc...')
#9 {main}
  thrown in /wp-config.load.php on line 46

WP-CLI error

  1. Theres no check on HTTP_HOST key when setting hostname, causing error on CLI with undefined index
  2. $argv doesn't appear to be available all the time (it's not for me), this could be because i was running via wp-cli and although i havent checked, it could possibly be dropping the $argv after it pushes it into the SERVER superglobal.
  3. You cannot pass --env= in all the wp-cli commands (help seems to be ok, but search & replace doesn't, as it errors about unknown parameters)

Got a fix for the 2 which i can PR, working on the 3rd

How about setting diffrent db prefixes based on env aswell?

Installing Multiple Blogs

good for using same codebase on diffrent domains

heres a sample that updates db prefix, needs some updates in wp config default to change the prefix to

$table_prefix  = 'wp_'.$country_prefix;


// Doesnt work with co.uk
function get_tld( $hostname ) {
    $tld = strrchr ( $hostname, "." );
    $tld = substr ( $tld, 1 );
    return $tld;
}

$country_prefix = '';
switch ( $hostname ) {

    case strpos($hostname,'domain.dev') !== false:
    define('WP_ENV', 'development');
    define('DOMAIN_CURRENT_SITE', 'domain.dev');
    break;

    case strpos($hostname,'domain.TLD') !== false:
    define('WP_ENV', 'staging');
    define('DOMAIN_CURRENT_SITE', 'domain.TLD');
    define('DB_NAME', 'DB');
    break;

    case strpos($hostname,'domain') !== false:
    $tld = get_tld( $hostname );
    define('WP_ENV', 'staging');
    define('DOMAIN_CURRENT_SITE', 'www.domain.' . $tld);
    define('DB_NAME', 'DB');
    $country_prefix = $tld . '_';
    break;

    case strpos($hostname,'domain.TLD') !== false:
    default: 
    define('WP_ENV', 'production');
    define('DOMAIN_CURRENT_SITE', 'www.domain.TLD');
}

Cannot determine current environment domain

Hi,

I keep getting the following error in my LIVE environments for some reason:

[23-Apr-2018 11:15:54 Australia/Brisbane] PHP Fatal error:  Uncaught Exception: Cannot determine current environment domain, make sure this is set in wp-config.env.php in /home/app/public_html/config/wp-config.load.php:100
Stack trace:
#0 /home/app/public_html/config/wp-config.load.php(124): load_environment_config()
#1 /home/app/public_html/wp-config.php(18): require_once('/home/app...')
#2 /home/app/public_html/wp-load.php(37): require_once('/home/app...')
#3 /home/app/public_html/wp-blog-header.php(13): require_once('/home/app...')
#4 /home/app/public_html/index.php(17): require('/home/app..')
#5 {main}
  thrown in /home/app/public_html/config/wp-config.load.php on line 100

IF my wp-config.env.php is configured like so:

$env = [
  'test' => [
    'domain' => 'domain_local.test',
    'path'   => '',
    'ssl'    => false,
  ],
  'staging' => [
    'domain'  => 'staging.domain_staging.com.au',
    'path'    => 'domain_live',
    'ssl'     => true,
  ],
  'live' => [
    'domain' => 'www.domain_live.com.au',
    'path'   => '',
    'ssl'    => true,
  ],
];

The only way to stop the error from happening is to modify LIVE environment to include a non-www version like this:

$env = [
  'test' => [
    'domain' => 'domain_local.test',
    'path'   => '',
    'ssl'    => false,
  ],
  'staging' => [
    'domain'  => 'staging.domain_staging.com.au',
    'path'    => 'domain_live',
    'ssl'     => true,
  ],
  'live' => [
    'domain' => ['www.domain_live.com.au', 'domain_live.com.au'],
    'path'   => '',
    'ssl'    => true,
  ],
];

Has anyone else come across this problem and found a solution?

Cheers,
Alex

SITE_URL and HOME are overridden

I have the set up in /core
So I put it in the env file.

But I do NOT want the url to show up including /core to customers.

Adding it to the environment file(s) does not work.

Over-escaping breaking wildcard domain matching

Warning: preg_match(): Compilation failed: unmatched parentheses at offset 7 in /app/public/wp-config.load.php on line 88

The '*' should be escaped to prevent over-escaping with preg_quote (otherwise the parenthesis of str_replace would be escaped)

$match = '/' . str_replace('*', '([^.]+)', preg_quote($domain_name, '/')) . '/';

It should look like this:

$match = '/' . str_replace('\*', '([^.]+)', preg_quote($domain_name, '/')) . '/';

Regards

wp cli database error

When I use ex. wp plugin list with wp-cli I get this error:

Error:

Error establishing a database connection

This either means that the username and password information in your wp-config.php file is incorrect or we can't contact the database server at . This could mean your host's database server is down.

  • Are you sure you have the correct username and password?
  • Are you sure that you have typed the correct hostname?
  • Are you sure that the database server is running?

If you're unsure what these terms mean you should probably contact your host. If you still need help you can always visit the WordPress Support Forums.

Any idea how to fix this?

Ignore plugins based on env

Would cool to ignore some plugins based on env.

For instance in development env I don't need jetpack or pixelyourside etc but I need them in production

can you use 'localhost' as the domain hostname?

Quick question... Can you use 'localhost' for the $hostname check, or you must setup vhosts/hosts file setup where there is a name like 'mywebsite.localhost' like your example.
Would be convenient to cover developers that don't setup a specific vhost for the Wordpress install/app.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.