Posted On: March 22, 2017

On most of the sites I create, I need to serve the site using multiple domains and force https. It is important for SEO purposes to only serve the site from a single domain. While other domains may point to the site, they will need to redirect to your primary domain. Same goes with serving the site using a subdomain like www. For example, https://domain.com should redirect to https://www.domain.com.

On Pantheon, you can handle this in wp-config.php for Wordpress or settings.php for Drupal. This code will go in the wp-config.php or settings.php file, depending on your CMS. Be sure to update your url, store it in a variable if you like.

if (isset($_ENV['PANTHEON_ENVIRONMENT'])) {
  if (($_SERVER['HTTPS'] === 'OFF') &&
    (php_sapi_name() != "cli")) {
    $is_ssl = !(!isset($_SERVER['HTTP_X_SSL']) ||
      (isset($_SERVER['HTTP_X_SSL']) &&
      $_SERVER['HTTP_X_SSL'] != 'ON'));
    if ($_ENV['PANTHEON_ENVIRONMENT'] == 'live') {
      if ($_SERVER['HTTP_HOST'] != 'www.domain.com' ||
        ($_SERVER['HTTP_HOST'] == 'www.domain.com' &&
        !$is_ssl)) {
        header('HTTP/1.0 301 Moved Permanently');
        header('Location: https://www.domain.com' . $_SERVER['REQUEST_URI']);
        exit();
      }
    } else if (!$is_ssl) {
      header('HTTP/1.0 301 Moved Permanently');
      header('Location: https://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
      exit();
    }
  }
}

This code will force https on the dev, test, and live environments. It will only force www and redirect to your primary domain on the live environment.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.