Jump to content
bernhard

Maintain separate configs for live/dev like a boss :)

Recommended Posts

Have you ever come across the situation where you needed to change your config.php file for local development? Have you ever come across this warning?

5aaa5dc1bd4d7_2018-03-1512_48_50-EditPage_Homehrd_w4y1.baumrock_com.png.36e7826396df488c67d6a672c7279712.png

Say goodbye to this little annoying tasks :)

Some of you might know that you can have a separate config-dev.php file for local development. This is nice, but also needs some setup (for example excluding this file for git upload) and there is still some danger of uploading this file to a place where it should not be... The other option was to keep the database settings for your live and dev server in sync - also not easy and maybe not the best...

My solution is as simple, fast and I think it should be even safer than the other options. Just put these lines at the end of your config.php file:

if(strpos($config->paths->root, 'C:/www/') === 0) {
  $config->dbUser = 'root';
  $config->dbPass = '';
  $config->httpHosts = [$_SERVER[HTTP_HOST]];
  $config->debug = true;
}
elseif(strpos($config->paths->root, '/var/www/vhosts/') === 0) {
  $config->httpHosts = [];
  $config->dbUser = 'XXX';
  $config->dbPass = 'XXX';
  $config->debug = false;
  
  /**
   * Redirect to HTTPS
   * ATTENTION: This will NOT work with ProCache enabled! Use .htaccess instead
   */
  if(empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "off"){
    $redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $redirect);
    exit();
  }
}
else die('wrong config.php');

Having a separate config-dev.php file also makes it necessary to keep both files in sync. That was my first idea: To include the original config and then overwrite settings. But it's just simpler the other way round: Using the default config.php file and overwriting settings there.

  • Like 7
  • Thanks 1

Share this post


Link to post
Share on other sites

Hi everybody 🙂

Just realized that redirecting to HTTPS does not work when ProCache is enabled (of course it does not work, but I didn't think of it...). The problem with redirecting via the default .htaccess rule is that it will also redirect to https on your dev environment. But you can easily exclude any domains from this redirect rule like this:

  # -----------------------------------------------------------------------------------------------
  # 9. If you only want to allow HTTPS, uncomment the RewriteCond and RewriteRule lines below.
  # -----------------------------------------------------------------------------------------------
  RewriteCond %{HTTPS} off
  RewriteCond %{HTTP_HOST} !.*\.test$ [NC]
  RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Maybe that helps someone else as well.

  • Like 2

Share this post


Link to post
Share on other sites

Another possibility is to use different names for htaccess files for local development and for live servers.

In your local httpd.conf you can set for AccessFilename something like

AccessFileName .htaccess.test

or

AccessFileName .htaccess.local

where you can define different settings for local development by keeping the .htaccess file untouched for online server settings.

  • Like 1
  • Thanks 1

Share this post


Link to post
Share on other sites

Thx. Didn't know about that. But I guess I'd then need to copy the whole .htaccess content over? Or does it load .htaccess additionally? Before or after the .htaccess? Or can that be defined?

Share this post


Link to post
Share on other sites

It only loads the defined .htaccess.local files. The regular .htaccess files are completly ignored. 

Yes, you may need to copy all locally required parts from regular to local AccessFiles. But I locally work with the pw distri htaccess file. I don‘t want to have settings included for caching or for ProCache. Also rewrites for different domain names to one final domain etc. only stays in the online file. Nothing of that is needed or explicitly must be avoided locally. 

Maintaining the .htaccess for online deploy exclusivly and add .htaccess.local to the .gitignore. 😀

  • Like 1
  • Thanks 1

Share this post


Link to post
Share on other sites

Good points! Htacces changes are very rare anyhow, so that would be totally fine. I'll think of that option in the future 🙂

  • Like 1

Share this post


Link to post
Share on other sites

Hi @bernhard

Here is my solution which uses the server name instead of a directory structure. So you are safe if you are changing paths or the OS where paths are different.

$base_url = $_SERVER['SERVER_NAME'];
$config->base_url = $base_url;
switch ($base_url) {
  case "p-jentschura.localhost":
  case "p-jentschura.acemanpc":
  case "p-info.localhost":
  case "p-info.acemanpc":
    $config->dbHost = 'localhost';
    $config->dbName = 'dbname';
    $config->dbUser = 'root';
    $config->dbPass = 'dbpass';
    $config->dbPort = '3306';
    $config->debug = false;
    $config->httpHosts = array(
      'p-jentschura.localhost',
      'p-jentschura.acemanpc',
      '192.168.178.16',
      '192.168.178.23',
      'localhost.p-jentschura'
    );
    break;
  default:
    // LIVE CONFIG
    $config->dbHost = '127.0.0.1';
    $config->dbName = 'dbname';
    $config->dbUser = 'dbuser';
    $config->dbPass = 'dbpass';
    $config->dbPort = '3306';
    $config->debug = false;
    $config->httpHosts = array(
      'p-jentschura.com',
      'www.p-jentschura.com',
      'p-jentschura.de',
      'www.p-jentschura.de',
      'p-jentschura.nl',
      'www.p-jentschura.nl',
      'p-jentschura.shop'
    );
}

 

  • Like 2

Share this post


Link to post
Share on other sites

Thx for sharing! I wonder why you don't use dev as default and only list the live server name as one case statement. Then you would not need to list all dev domains and could even create new ones without changing the config 🙂

Share this post


Link to post
Share on other sites

LOL. This is because I have far more domains on the live server and didn't want to write them all. Most of my dev server settings could also be omitted; I only use one dev domain ATM.

Share this post


Link to post
Share on other sites

Nice thinking @bernhard!

I have one config.php with reads a config.ini file using "parse_ini_file" which is one level up from /public/. No passwords in my Version Control and the same config file for all installs. 

  • Like 2
  • Thanks 1

Share this post


Link to post
Share on other sites

I've now came up with this setup which works really well for me:

/site/config.php (can safely be committed to GIT)

<?php
if(!defined("PROCESSWIRE")) die();

/*** SITE CONFIG *************************************************************************/

$config->debug = false;
$config->prependTemplateFile = '_init.php';
$config->appendTemplateFile = '_main.php';

/*** INSTALLER CONFIG ********************************************************************/

$config->dbHost = 'localhost';
$config->dbPort = '3306';
$config->chmodDir = '0755'; // permission for directories created by ProcessWire
$config->chmodFile = '0644'; // permission for files created by ProcessWire 
$config->timezone = 'Europe/Vienna';

// include config file from outside of the repo
include('../config.php');

../config.php DEV (one file for all laragon hosted sites on my local machine)

<?php
$config->dbUser = 'root';
$config->dbPass = '';
$config->httpHosts = [$_SERVER['HTTP_HOST']];
$config->debug = true;

switch($_SERVER['SERVER_NAME']) {
  case 'www.XXX.test':
    $config->dbName = 'XXX';
    $config->userAuthSalt = 'XXX';
    $config->installed = 123456789;
    break;
  [...]
}

../config.php LIVE (one file for each vhost)

<?php
$config->dbName = 'XXX';
$config->dbUser = 'XXX';
$config->dbPass = 'XXX';
$config->httpHosts = ['www.XXX.com'];
$config->userAuthSalt = 'XXX';
$config->installed = 123456789;
setlocale(LC_ALL,'en_US.UTF-8');

Thx for that ideas @arjen and @jens.martsch!

  • Like 2
  • Thanks 1

Share this post


Link to post
Share on other sites

In regards to dev vs live htaccess, you can also use htaccess's "if" conditional for blocks of code you want to selectively enable/disable depending on the site being loaded.  By doing so, you don't need two separate htaccess files to maintain.

When using ProCache combined with it's htaccess recommendations at the top, I wrap it inside a conditional like this:

#################################################################################################
# ProcessWire ProCache recommended .htaccess tweaks for expires and gzip performance settings. 
# PWPC-3.0 Keep this line here for ProCache identification purposes. 
#################################################################################################
<If "%{HTTP_HOST} == 'my-live-website.com'">
  ...the code here...
</If>

 

  • Like 4
  • Thanks 2

Share this post


Link to post
Share on other sites

I use an IDE and found it stressful to have to work-around deploying config.php

This is how I found your thread. Thank you!

I integrated your solution into my own workflow and came up with this to share back here:

/site/config.php (like @bernhard except last line) 

// include config file from outside of the repo
$client = 'config-' . end(explode('/',__FILE__, -2));
include("../$client.php");

 The PHP end() function and the minus 2 in the explode(), always gets the URI domain base. (As long as PW keeps it there.)

Since my usual deployment flow is from ABC.dev -> test.mybox.com/ABC -> ABC.com

...in my root folder, safely out of reach (like @bernhard's concept), I then create 3 files each containing config deployment differences.

../config-ABC.dev.php  and  ../config-ABC.php  and ../config-ABC.com.php

For those also using PHPStorm, since these files are located out of project, I would add them in Favorites. (And add it's root folders in Deployment Mappings).

I can then easily make use of IDE features like "Compare Two Files", "Sync with Deployed to", etc. Removing doubts about what config property I may have missed across the board. No more stress.

  • Like 3

Share this post


Link to post
Share on other sites

Little tweak that you can add to your config.php on DEV to support bootstrapping of PW (in that case there is no SERVER_NAME set and you need to define it manually):

<?php
if(!defined("PROCESSWIRE")) die();

// make bootstrapping possible
$const = get_defined_constants(true);
$host = $const['user']['host'] ?: $_SERVER['SERVER_NAME'];

$config->dbUser = 'root';
$config->dbPass = '';
$config->httpHosts = [$_SERVER[HTTP_HOST]];
$config->debug = true;

switch($host) {
  case 'www.foo.bar':
    $config->dbName = 'foo';
    $config->userAuthSalt = 'bar';
    break;
}

Then you can execute any script like this:

<?php namespace ProcessWire;
define('host', 'www.foo.bar');
include('index.php');
foreach($pages->find('limit=100') as $p) {
  echo $p->path . "\n";
}

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...