2012-09-09 68 views
0

现在,我有一个使用两种语言(法语和英语)的网站。。多语言网站的htaccess技巧

它目前的工作方式是,如果有人去mysite.com/folder/file.php例如,file.php仅仅是计算出使用哪种语言的脚本,得到它自己的路径和文件名(file.php),并担任了mysite.com/en/folder/file.php(如果语言是英语)。但是,在URL中显示的内容仍然是mysite.com/folder/file.php

对于任何文件夹和任何文件,使用相同的脚本。如果我想添加一个新文件,我必须将文件添加到用户输入浏览器的文件夹以及enfr文件夹中。

我可以做一些.htaccess技巧,以便无论输入什么URL,打开一个.php文件,检查所请求的语言和文件夹/文件,然后提供正确的语言文件?

下面是为URL中的任何文件提供的php文件。

<?php 

// Get current document path which is mirrored in the language folders 
$docpath = $_SERVER['PHP_SELF']; 

// Get current document name (Used when switching languages so that the same 
current page is shown when language is changed) 
$docname = GetDocName(); 

//call up lang.php which handles display of appropriate language webpage. 
//lang.php uses $docpath and $docname to give out the proper $langfile. 
//$docpath/$docname is mirrored in the /lang/en and /lang/fr folders 
$langfile = GetDocRoot()."/lang/lang.php"; 
include("$langfile"); //Call up the proper language file to display 

function GetDocRoot() 
{ 
$temp = getenv("SCRIPT_NAME"); 
$localpath=realpath(basename(getenv("SCRIPT_NAME"))); 
$localpath=str_replace("\\","/",$localpath); 
$docroot=substr($localpath,0, strpos($localpath,$temp)); 
return $docroot; 
} 

function GetDocName() 
{ 
$currentFile = $_SERVER["SCRIPT_NAME"]; 
$parts = Explode('/', $currentFile); 
$dn = $parts[count($parts) - 1]; 
return $dn; 
} 

?> 

回答

1

一个常见的解决方案是让网站(的index.php)的根找出优选语言,然后重定向到包含语言代码的URL。如果您的文件被磁盘上的语言分隔,则可以直接请求它们。

或者你可以在.htaccess中添加一个简单的正则表达式或您的主机设置抢出语言所请求的URL,并把所有类似的请求到一个文件:

RewriteEngine On 
RewriteRule ^/(.+)/folder/file.php$ /folder/file.php?lang=$1 

然后引用$_GET['lang']在PHP中看到要求哪种语言。您可能希望扩大此范围,以便对网站上的所有类似文件进行更一般化处理,例如:

RewriteRule ^/(.+?)/(.+)\.php$ /$2.php?lang=$1