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

Last modified by thetoine on Wed, July 21, 2010 21:21
Source|Old Revisions  

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:

  1. require_once 'app/Mage.php';
  2.  
  3. /* Determine correct language store based on browser */
  4. function getStoreForLanguage()
  5. {
  6.     if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  7.         foreach (explode(",", strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE'])) as $accept) {
  8.             if (preg_match("!([a-z-]+)(;q=([0-9.]+))?!", trim($accept), $found)) {
  9.                 $langs[] = $found[1];
  10.                 $quality[] = (isset($found[3]) ? (float) $found[3] : 1.0);
  11.             }
  12.         }
  13.         // Order the codes by quality
  14.         array_multisort($quality, SORT_NUMERIC, SORT_DESC, $langs);
  15.         // get list of stores and use the store code for the key
  16.         $stores = Mage::app()->getStores(false, true);
  17.         // iterate through languages found in the accept-language header
  18.         foreach ($langs as $lang) {
  19.             $lang = substr($lang,0,2);
  20.             if (isset($stores[$lang]) && $stores[$lang]->getIsActive()) return $stores[$lang];
  21.         }
  22.     }
  23.     return Mage::app()->getStore();
  24. }
  25.  
  26. /* Auto redirect to language store view if request is for root */
  27. if ($_SERVER['REQUEST_URI'] === '/') {
  28.     header('Location: '.getStoreForLanguage()->getBaseUrl());
  29.     exit;
  30. }
  31.  
  32. #Varien_Profiler::enable();
  33.  
  34. #Mage::setIsDeveloperMode(true);
  35.  
  36. #ini_set('display_errors', 1);
  37.  
  38. umask(0);
  39. 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.