Tuesday, 27 May 2014

Multilanguage sub-domain. How to implement?



You can have HTACCESS perform a mod_rewrite rule identify these instances, or you can apply a blanket rule within HTACCESS and then have PHP do the heavy lifting from there. Or a combination of the two.

HTACCESS mod_rewrite Solution

RewriteEngine On
RewriteCond %{HTTP_HOST} !^(www.)?abc.com$ [NC]
RewriteCond %{HTTP_HOST} ^(.+).abc.com$
RewriteRule ^(.*)$ $1?lang=%1 [QSA,L]
Examples using this rule:
No Change - These are assumed as the Base
http://www.abc.com
  ==> http://www.abc.com
http://abc.com
  ==> http://abc.com
Language Coded Subdomains
http://de.abc.com
  ==> http://de.abc.com/?lang=de
http://esp-es.abc.com
  ==> http://esp-es.abc.com/?lang=esp-es
Language Coded Subdomains with filename & query
http://esp-us.abc.com/filename.htm
  ==> http://esp.us.abc.com/filename.htm?lang=esp-us
http://fr.abc.com/filename.htm?name=value
  ==> http://fr.abc.com/filename.htm?lang=fr&name=value

PHP Solution

Include this code somewhere towards the top of the page (before language-specific content is generated).
<?php
$lang = false;
if( preg_match( '/^(.+)\.abc.com$/' , $_SERVER['HTTP_HOST'] , $matches )
    && count( $matches )==2
    && $matches[1]!='www' ){
  $lang = $matches[1];
}
You can then use the $lang variable (which will be false if either A) no subdomain, or B) the "www" subdomain is used. Additionally, you can check the value of the $lang variable against an array of acceptable languages, and, if it is not present, again, reset it to false.


Share:

No comments:

Post a Comment