How can I autodetect the user's browser language and redirect to the "right" store view in Magento Commerce Cloud?
Thanks!
2 Answers
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.
-
1I have a multisite setup so my
magento-vars.php
looks a bit different but you gave me the idea of how to :-). Thanks Commented Aug 17, 2021 at 9:26
I think you could try to using javascript for detecting the user language
var language = window.navigator.userLanguage || window.navigator.language;
alert(language); //works IE/SAFARI/CHROME/FF
If the user language is different from the current store view language, you will redirect to the correct URL using javascript.