Magento Cloud – Autodetect Browser Language and Redirect

magento2-cloudmagento2.4

How can I autodetect the user's browser language and redirect to the "right" store view in Magento Commerce Cloud?
Thanks!

Best Answer

If you can reliably use the HTTP header "Accept-Language" then there may be two ways of doing it (rely on the HTTP header availability, so please validate the fallback.)

For example:

Accept-Language: en-US,en;q=0.5

Using Fastly Custom VCLs

Fastly provides a way of reading this header, process/filter it and apply custom redirect. https://docs.fastly.com/en/guides/accept-language-header-vcl-features

Using ./magento-vars.php File

PHP provides the ability to parse the HTTP Accept-Language header https://www.php.net/manual/en/locale.acceptfromhttp.php

  • $locale = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
  • $locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);

You may write your own custom logic on ./magento-vars.php and do the necessary redirections. ./magento-vars.php has the visibility to $_SERVER, $_ENV, $_COOKIE etc.

Multi-store setup and sample snippets can be found on this DevDocs link: https://devdocs.magento.com/cloud/project/project-multi-sites.html#modify-magento-variables

For an example:

<?PHP


// enable, adjust and copy this code for each store you run
// Store #0, default one

// ./magento-vars.php

function customStoreLogic()
{
    $storeView = false;
    if (!isset($_SERVER['HTTP_HOST'])) {
        return false;
    }

    $locale = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);

    switch ($locale) {
        case "en_US":
            $storeView = 'us_store';
            break;
        default:
            $storeView = 'default';
            break;
    }
    return $storeView;
}

$storeView = customStoreLogic();

if ($storeView) {
    $_SERVER["MAGE_RUN_CODE"] = $storeView;
    $_SERVER["MAGE_RUN_TYPE"] = "store";
}   

Hope this helps.

Related Topic