How to add multilingual support rewrite rules using htaccess?

时间:2015-06-25 19:01:25

标签: php .htaccess

My website urls structure is based like this www.domain.com/page1 -> default language where all my pages are located in the root folder. I want to add multilingual support and create folders for each language, containing the file with the translated text. So when a language is requested, looks in the appropriate language folder and display it. www.domain.com/lang/page1 -> 2 chars language How can I do this, keeping the english language as the default language? Currently this is my htaccess RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d ErrorDocument 404 /404.php RewriteRule ^([^\.]+)$ $1.php [NC,L]

1 个答案:

答案 0 :(得分:0)

You can use language redirection by .htaccess. An example for German: RewriteEngine on RewriteCond %{HTTP:Accept-Language} (de) [NC] RewriteRule .* https://google.de [L] Why are not you just using PHP? You can get the browser language, just look at this function: public static function getBrowser ($languages, $accept) { // HTTP_ACCEPT_LANGUAGE is defined in // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 // pattern to find is therefore something like this: // 1#( language-range [ ";" "q" "=" qvalue ] ) // where: // language-range = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" ) // qvalue = ( "0" [ "." 0*3DIGIT ] ) // | ( "1" [ "." 0*3("0") ] ) preg_match_all("/([[:alpha:]]{1,8})(-([[:alpha:]|-]{1,8}))?" . "(\s*;\s*q\s*=\s*(1\.0{0,3}|0\.\d{0,3}))?\s*(,|$)/i", $accept, $hits, PREG_SET_ORDER); // default language (in case of no hits) is the first in the array $bestlang = $languages[0]; $bestqval = 0; foreach ($hits as $arr) { // read data from the array of this hit $langprefix = strtolower ($arr[1]); if (!empty($arr[3])) { $langrange = strtolower ($arr[3]); $language = $langprefix . "-" . $langrange; } else $language = $langprefix; $qvalue = 1.0; if (!empty($arr[5])) $qvalue = floatval($arr[5]); // find q-maximal language if (in_array($language,$languages) && ($qvalue > $bestqval)) { $bestlang = $language; $bestqval = $qvalue; } // if no direct hit, try the prefix only but decrease q-value // by 10% (as http_negotiate_language does) else if (in_array($languageprefix,$languages) && (($qvalue*0.9) > $bestqval)) { $bestlang = $languageprefix; $bestqval = $qvalue*0.9; } } return $bestlang; } I use it myself with this call: $browserLanguage = getBrowser($supportedLanguages, $_SERVER['HTTP_ACCEPT_LANGUAGES']; For $supportedLanguages, you can use codes like de, en-gb or en-us.