2012-09-09 69 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