Friday, July 22, 2011

Multi-language support for a website

I am not a frontend developer, just stumbled upon this problem helping out my friend to set up a website that is supposed to serve multi-language content based on the language setting of the user. This is actually an interesting problem (maybe already solved and I did not know).

There are several different solutions that I found through after doing some study:

- Server side detection based on Accept-Language request header

For example, apache mod_negotiation allows you to define a set of html pages in different languages (index.html.en, index.html.zh, etc.) and based on the user preferences from Accept-Language header, apache picks the right index.html language page to return.

You can also use mod_rewrite to perform the similar trick. Just set up the rewrite condition based on the value of the AL header and map to the correct language.

- Client side detection and action using JavaScript and navigator object.

In IE, navigator.userLanguage returns the operating system region and language setting, in Firefox, Opera, Safari and Chrome, navigator.language returns the browser application language setting. So, we can use them to get the user language and decide what language content to return.

For example, this code snippet (borrowed from an example on jsfiddle) defines multi-language content on the same page and use JavaScript to show or hide it based on the detected language.

The drawback of this approach is that a large part of the content is not needed and invisible. It is a waste of time to download.

Another approach is to use JavaScript to redirect to individual language content pages using window.location.href="redirected_page_url" or window.location.replace("redirected_page_url"). See Location object for more details on how to use them. The downside is this approach may not be search engine friendly (spiders may not be able to follow redirection).

One last note how to test multi-lang website. I tried in Firefox, simple change the language ranking in Preferences->Content Tab->Language Choose button and FF will start sending different Accept-Language headers based on the ranking. You can also play with the operating system language settings.