5

In the general.php config file, I can target settings for multi-environments like so:

return array(
  '*' => array(
    'devMode' => false
  ),

  '.loc' => array(
    'devMode' => true
  )
);

Is it possible to do something similar in the routes.php file too?

return array(
  '*' => array(
    'test' => 'index'
  ),

  '.loc' => array(
    'test' => '_test/index'
  )
);

I don't want to differentiate the locales, but the environment instead. I know it's possible to query how content gets included within the templates themselves. I just wondered if this is possible instead... I don't actually have a use-case example.

Maybe a time will arise where I want to allow certain content to be accessible for 'staging.' domains only.

Thanks,

Mark

6

The routes.php config file doesn't support multi-environment setups in the manner that general.php or db.php does – in other words, your example code using a multidimensional array would throw an error.

As a workaround, you can write some PHP in your routes.php file. For simple stuff, a ternary operator may suffice:

return array(
    'test' => strpos(CRAFT_ENVIRONMENT, '.loc') !== false ? '_test/index' : 'index', 
);

For more complex stuff, you could set up different arrays of routes for different enviroments, and maybe do some merging:

$routes = array(
    'foo' => '_foo',
    'bar' => '_bar',
);

$devRoutes = array(
    'baz' => '_baz',
);

$stagingRoutes = array(
    'baz' => '_staging/baz',
);

if (strpos(CRAFT_ENVIRONMENT, '.loc') !== false) {
    $routes = array_merge($routes, $devRoutes);
} else if (strpos(CRAFT_ENVIRONMENT, '.staging') !== false) {
    $routes = array_merge($routes, $stagingRoutes);
}

return $routes;

If you're wondering about the CRAFT_ENVIRONMENT constant, that'll default to your hostname (e.g. myawesomesite.loc) unless you explicitly set it to something else before bootstrapping Craft (e.g. in your index.php file). The simple strpos(CRAFT_ENVIRONMENT, $env) test is how Craft merges multi-enviroment configs (e.g. from general.php) under the hood.

  • 1
    Thanks for the detailed answer; this works. I never even knew you could query the CRAFT_ENVIRONMENT like that. In practice I can see if this were used as a way to redirect users somewhere generic (like in my example), there would be no way to define a Canonical link within the template. So very bad for SEO. In very rare cases this might be handy; for now I'm just happy it is possible and clean to do. Thanks again. – Mark Notton Jul 24 '16 at 12:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.