diff --git a/_includes/2020/templates/Head.php b/_includes/2020/templates/Head.php index 769a9294..4c4cb9ae 100644 --- a/_includes/2020/templates/Head.php +++ b/_includes/2020/templates/Head.php @@ -39,10 +39,7 @@ static function render($fields = []) { // Redirect to /en/... if not a supported locale; this needs to be emitted // as a HTTP header before first content byte. if(Locale::invalidLocale()) { - if(preg_match('/^\\/[^\/]+\\/(.+)$/', $_SERVER['REQUEST_URI'], $matches)) { - header("Location: /" . Locale::DEFAULT_LOCALE . "/" . $matches[1]); - return; - } + Locale::redirectLocale(); } ?> diff --git a/_includes/locale/Locale.php b/_includes/locale/Locale.php index 558bba75..5d6d17ff 100644 --- a/_includes/locale/Locale.php +++ b/_includes/locale/Locale.php @@ -62,22 +62,39 @@ public static function invalidLocale() { return self::$invalidLocale; } + /** + * Redirect page to specified locale. Default to 'en' if unspecified + * @param $newLocale + */ + public static function redirectLocale($newLocale = Locale::DEFAULT_LOCALE) { + if(preg_match('/^\\/[^\/]+\\/(.+)$/', $_SERVER['REQUEST_URI'], $matches)) { + header("Location: /" . $newLocale . "/" . $matches[1]); + return; + } + } + /** * Set the current locale based on the first path component * //rest/of/path for the current page URL */ private static function setLocaleFromURL() { // First component of the URL is always the locale - if(preg_match('/^\\/(([a-z]{2,3})(-([A-Za-z]{4}))?(-([a-z]{2}|[0-9]{3}))?)\\//', $_SERVER['REQUEST_URI'], $matches)) { - if(!isset(DISPLAY_NAMES[$matches[1]])) { - // Note: this is an unsupported locale, so we'll end up redirecting in head.php to /en/... + if(preg_match('/^\/(([a-z]{2,3})(-([A-Z][a-z]{3}))?(-([A-Z]{2}|[0-9]{3}))?)\//', $_SERVER['REQUEST_URI'], $matches)) { + $fallbackLocales = self::calculateFallbackLocales($matches[1]); + if (isset($fallbackLocales[0])) { + $pageLocale = $fallbackLocales[0]; + if ($pageLocale != $matches[1]) { + // Redirect if using a fallback locale + Locale::redirectLocale($pageLocale); + } + } else { + // Note: this is an unsupported locale, so we'll end up redirect in head.php to /en/... $pageLocale = Locale::DEFAULT_LOCALE; self::$invalidLocale = true; - } else { - $pageLocale = $matches[1]; } } else { $pageLocale = Locale::DEFAULT_LOCALE; + // Don't set invalidLocale so pages like /_test/ work } self::setLocale($pageLocale); }