cancel
Showing results for 
Search instead for 
Did you mean: 

How to automatically redirect to a store view based on the browser language

How to automatically redirect to a store view based on the browser language


Introduction
This article assumes you have a store with multiple store views that represent different languages, that you have enabled store code in the urls (Admin Panel → System → Configuration → Web → Url Options → Add store code to Urls → Yes) and you want to redirect your visitors that go to the root store Url to the most appropriate language store view based on their browser locale setting.

For example, if a user types www.mystore.com and their browser is set to french locale they would be redirected to www.mystore.com/fr/. If there was no store view with a match to their browser language locale then the default store would be used as the fallback, e.g. www.mystore.com/en/.

Configuration Requirements
Your web server must have mod_rewrite enabled.
Enable Url rewriting (Admin Panel → System → Configuration → Web → Url Options → Use Web Server Rewrites → Yes).
Enable store code in the urls (Admin Panel → System → Configuration → Web → Url Options → Add store code to Urls → Yes).
Store View Setup
For each store view you must set the code to the 2-letter browser locale code you wish to match upon. For example, we’ll create two store views (english and spanish):

Create the default English store view:

Go to Manage Stores (Admin Panel → System → Manage Stores).
Create a new store view
Set the store and name to appropriate values (e.g. Default Store and English)
Set the code to the country code, in this case en. This is the value that will be matched to the browser locale settings.
Keep the sort order as zero (0) as this will be our default language.
Create the Spanish store view:

Create a new store view
Set the store and name to appropriate values (e.g. Default Store and Spanish)
Set the code to the country code, in this case es. This is the value that will be matched to the browser locale settings. For a list of valid 2 letter country codes see http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes.
Set the sort order two one (1).
You may have any number of additional store views, simply repeat the process above using the appropriate country code.

Before continuing, test that the store view urls work by typing the address into your browser. For example, www.mystore.com/en/ and www.mystore.com/es/ should both work.

Modifying index.php
To enable the automatic redirect of a visitor when they visit the main store url (e.g. www.mystore.com) with a browser that is set to use spanish as their desired language we need to modify the index.php as follows:

require_once 'app/Mage.php';
 
/* Determine correct language store based on browser */
function getStoreForLanguage()
{
    if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
        foreach (explode(",", strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE'])) as $accept) {
            if (preg_match("!([a-z-]+)(;q=([0-9.]+))?!", trim($accept), $found)) {
                $langs[] = $found[1];
                $quality[] = (isset($found[3]) ? (float) $found[3] : 1.0);
            }
        }
        // Order the codes by quality
        array_multisort($quality, SORT_NUMERIC, SORT_DESC, $langs);
        // get list of stores and use the store code for the key
        $stores = Mage::app()->getStores(false, true);
        // iterate through languages found in the accept-language header
        foreach ($langs as $lang) {
            $lang = substr($lang,0,2);
            if (isset($stores[$lang]) && $stores[$lang]->getIsActive()) return $stores[$lang];
        }
    }
    return Mage::app()->getStore();
}
 
/* Auto redirect to language store view if request is for root */
if ($_SERVER['REQUEST_URI'] === '/') {
    header('Location: '.getStoreForLanguage()->getBaseUrl());
    exit;
}
 
#Varien_Profiler::enable();
 
#Mage::setIsDeveloperMode(true);
 
#ini_set('display_errors', 1);
 
umask(0);
Mage::run();
There are two parts to the code we have added. The first is a method called getStoreForLanguage which does the following:

Parse the HTTP_ACCEPT_LANGUAGE header (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4) sent by the browser for a set of desired languages and the priority code for each.
Sort the priority codes so the most desired language is first.
Iterate through the store views to find a store view that has a 2 letter ISO 639-2 country code that matches the desired language.
Return the store view if found or the default store view if not.
The second part of the code runs for each request and checks to see if we are requesting the root url and if so calls the above method to determine where we should send the visitor. This assumes your web store is located at the root level, if you installed Magento into a directory such as /magento (e.g. www.mystore.com/magento) you should change this line to be /magento instead.

Testing the detection
There are two ways you can test to see if the changes you have made work.

The first method is to change your browser language settings. Instructions for this can be found at http://www.w3.org/International/questions/qa-lang-priorities.
The second (and easier way) is to use the Firefox plugin Quick Locale Switcher at http://addons.mozilla.org/en-US/firefox/addon/1333.

5 REPLIES

Re: How to automatically redirect to a store view based on the browser language

Hey buddy,

 

I tried your solution yet i get this error:

 

It seems like the browser wants to redirect because if i type in: domain.com it goes for a second to domain.com/nl but after a second an error appears:

"There has been an error processing your request. Exception printing is disabled by default for security reasons."

If i look at the error in the log file i see this:

 

a:4:{i:0;s:53:"Mage registry key "application_params" already exists";i:1;s:349:"#0 /var/www/webroot/ROOT/app/Mage.php(223): Mage::throwException('Mage registry k...')
#1 /var/www/webroot/ROOT/app/code/core/Mage/Core/Model/App.php(338): Mage::register('application_par...', Array)
#2 /var/www/webroot/ROOT/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#3 /var/www/webroot/ROOT/index.php(129): Mage::run('', 'store')
#4 {main}";s:3:"url";s:4:"/nl/";s:11:"script_name";s:10:"/index.php";}

 

Re: How to automatically redirect to a store view based on the browser language

Another way is to automatically redirect to a store view based on visitors location. Our GeoIP Store and Currency Switcher use for this MaxMind's GeoIP database

Re: How to automatically redirect to a store view based on the browser language

Thanks for sharing the code, You can also try our Magento Language Switcher that allows merchants to automatically change the language and currency of the store based on visitors location.

Re: How to automatically redirect to a store view based on the browser language

Hi!

There is another option: you can use this GeoIP Redirect extension - https://www.magentocommerce.com/magento-connect/geoip-redirect-by-amasty.html

It redirects customers to the right store view and currency based on the clients' location.

Was my answer helpful? You can accept it as a solution.
200+ professional extensions for M1 & M2 with free lifetime updates!

Re: How to automatically redirect to a store view based on the browser language

You can redirect customers to a store view of their browser language to give them a personalized shopping experience.  First of all, there are some configuration requirements which you need to take care of before making any coding changes. 

 

  • Your web server must have mod_rewrite enabled.
  • Enable URL rewriting (Admin Panel → System → Configuration → Web → Url Options → Use Web Server Rewrites → Yes).
  • Enable store code in the urls (Admin Panel → System → Configuration → Web → Url Options → Add store code to Urls → Yes).

You can setup multiple store views from Admin panel and set the code to the 2-letter browser locale code you want to match upon.

 

After that you can modify index.php to enable redirection based upon user location.