.htaccess多语言网站技巧


.htaccess tricks for multi-language website

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

目前的工作方式是,例如,如果有人转到mysite.com/folder/file.phpfile.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;
}
?>

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

或者,您可以在.htaccess或主机设置中添加一个简单的regex,从请求的URL中获取语言,并将所有类似的请求发送到一个文件:

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

然后在PHP中引用$_GET['lang']来查看请求的语言。你可能想将其扩展到更通用的网站上的所有类似文件,例如:

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