diff --git a/README.md b/README.md index 482e302..df173f3 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,11 @@ elseif (Environment::isLocal()) { // Set some development environment settings overrides. } +// Redirect any internal platform domains to a preferred domain. +if (Environment::isProduction()) { + Environment::enforceDomain('www.example.com'); +} + // Include a environment-specific settings file. if ($environment = Environment::getEnvironment()) { $settings_file = 'settings.' . $environment . '.php'; diff --git a/src/Environment.php b/src/Environment.php index eaf291a..2f51cdc 100644 --- a/src/Environment.php +++ b/src/Environment.php @@ -180,4 +180,43 @@ public static function getComposerLockFilename(): string $filename = static::getComposerFilename(); return pathinfo($filename, PATHINFO_FILENAME) . '.lock'; } + + /** + * Get the current domain name. + * + * @return string + * The current domain name. + * + * @todo This could be improved. See https://stackoverflow.com/questions/1459739. + */ + public static function getCurrentDomain(): string + { + static $host; + if (!isset($host)) { + $host = $_SERVER['HTTP_X_FORWARDED_HOST'] ?? $_SERVER['HTTP_HOST']; + } + return $host; + } + + /** + * Redirect requests to a preferred domain. + * + * This will not redirect CLI requests. + * + * @param string $domain + * The preferred domain name. + */ + public static function enforceDomain(string $domain): void + { + if (!static::isCli() && static::getCurrentDomain() !== $domain) { + // Name transaction "redirect" in New Relic for improved reporting. + if (extension_loaded('newrelic')) { + newrelic_name_transaction('redirect'); + } + + header('HTTP/1.0 301 Moved Permanently'); + header('Location: https://' . $domain . $_SERVER['REQUEST_URI']); + exit(); + } + } } diff --git a/src/Pantheon.php b/src/Pantheon.php index 43f4eee..26273aa 100644 --- a/src/Pantheon.php +++ b/src/Pantheon.php @@ -65,6 +65,6 @@ public static function isMultidev(): bool */ public static function isCustomDomain(): bool { - return isset($_SERVER['HTTP_HOST']) && !str_ends_with($_SERVER['HTTP_HOST'], static::PLATFORM_DOMAIN); + return !str_ends_with(Environment::getCurrentDomain(), static::PLATFORM_DOMAIN); } }