Learn

Environments

Alter your site based on the URL viewing it.

Environments allow you to change settings based upon the URL accessing the site. This becomes helpful when using a multiple-server workflow. In that instance, environments would let you easily change values for your development, staging, and production servers.

You define environments in your main settings.yaml file, like so:

_environments:
  dev:
    - 'http://localhost*'
    - '*.dev'
    - '*.localip'

  staging:
    - 'staging.mysite.com'

In this example, if you were to set up and view your website from the URL http://mysite.dev, the dev environment would be triggered. Likewise, viewing the site from http://staging.mysite.com would trigger the staging environment.

Note that only one environment can be active at any one time, and Statamic will try to match environments from top to bottom. This means that in the above example, if a URL somehow matched an option in both dev and staging, the dev environment would be triggered because it was matched first. As soon as Statamic matches an environment in your list, it stops looking for more.

Once an environment has been activated, two things become available:

  1. The is_[environment] variable becomes true, where [environment] is the name of the environment you’ve defined — for example, it would be is_dev in your dev environment
  2. Statamic will overwrite your settings and global variables with those defined in the related environment YAML file in your environments configuration folder (at _config/environments/[environment].yaml) where [environment] is the name of the environment you’ve defined

Best Practices

Best practice for environments is to have production-level values be the defaults for all of the settings in your main configuration files, overriding them as needed for other environments (such as dev or staging).

Also, while is_[environment] variables will exist when an environment is activated, it’s a good idea to limit their use. If, for example, you wish to only have analytics running in production, wrap your analytics code in something that looks like this:

{{ if !disable_analytics }}
   {{# your analytics code here #}}
{{ endif }}

Then, in your dev and staging environment YAML files, add:

disable_analytics: true

This technique provides a number of advantages:

  • Production values default to false, which enables analytics
  • If you wish to enable analytics for dev, for example, maybe to test out something fishy with them, rather than searching through your code to find is_dev at the right spots, you can simply change your disable_analytics variables to false and be done with it
  • This is a similar practice to JavaScript capability testing instead of browser testing

This article was last updated on September 13th, 2016. Find an error? Please let us know!