Subdomain redirection based on browser language

1

What is the correct method of directing the navigation of a website to a specific page based on the language of the user's browser?

I have a website (www.site.com) with the default language in English and I need it, when it is accessed in a browser with the Portuguese language (pt-br), it redirects the navigation to the subdomain that I created and already I hosted the translated files (br.site.com).

The same for Spanish (es.site.com) and Italian (it.site.com).

What should I do? What kind of code should I enter?

PS: I already have the pages translated and hosted in their subdomains . I just need to know how to identify the browser language and auto-route.

How is this done in the code? Javascript? PHP? Ajax? Via htacess? Does anyone have this line of code to share?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My site</title>
</head>
<body>
    <p>The book is on the table.</p>
</body>
</html>
    
asked by anonymous 02.03.2017 / 15:09

2 answers

3

You can do the following (put this only in the English site, which is the default, not to enter an infinite loop):

const sites = {
  'pt-br': 'http://br.site.com',
  'it': 'http://it.site.com',
  'es': 'http://es.site.com'
};

var lang = navigator.language || navigator.userLanguage;
lang = lang.toLowerCase(); // é possível a lang do navegador ser por ex: pt-BR
if(typeof sites[lang] !== 'undefined') {
  // window.location.replace(sites[lang]);
  alert('redirecionar para ' +sites[lang]);
}

Browser Language Codes

I commented the redirect, but that's what you should use.

I convert the browser's return language to lowercase because it is very possible that it is for example: pt-BR , en-US , and we must have in agreement with the keys of our object sites

    
02.03.2017 / 15:28
0

You can use javascript for this, see example below:

var lang = navigator.language;
alert(lang);
    
02.03.2017 / 15:17