2012-02-19 39 views
1

我想在URL中指定用户的语言首选项。 是否有可能使用.htaccess重写规则添加一个网段到网址,如果丢失。在URL中强制用户的语言偏好 - 重写?

URL通常应具有这种结构

mysite.com/directory/en 
mysite.com/directory/fr 
mysite.com/directory/en/about_us.php 
mysite.com/directory/fr/about_us.php 

如果语言不存在,我想自动变换网址默认为英语。

mysite.com/directory     
>> should be transformed to mysite.com/directory/en 

mysite.com/directory/about_us.php 
>> should be transformed to mysite.com/directory/en/about_us.php 

实施例:

RewriteEngine On 

# don't redirect 

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-l 


RewriteRule !^(fr|en)/ /... something... 

# redirect 
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L] 

** * ** 一天后 ** * ** * ****

有人可以帮助我准确地了解迈克尔的解决方案正在做,以及如何更改htaccess的,如果我移动到新的子目录

mysite.com/directory     
>> should be transformed to mysite.com/directory/en 

mysite.com/directory/subdirectory/about_us.php 
>> should be transformed to mysite.com/directory/en/subdirectory/about_us.php 

...

# If the URL doesn't match /xx/otherstuff 
# !^([a-z]{2}) - exactly two alpha characters not at the beginning of the string 
# (.*)$ - store the result found above as $1 
RewriteCond %{REQUEST_URI} !^([a-z]{2}/)(.*)$ 

# Rewrite to /en/ 
# ^(.+)$ - begins with 
# http://%{HTTP_HOST}/en/$1 - replace with http://hostname/en 
# L = Last Stop the rewriting process immediately and don't apply any more rules. 
# R = Redirect Forces an external redirect, optionally with the specified HTTP status code 
# QSA - Query String Append - forces the rewrite engine to append a query string part of the substitution string to the existing string 
RewriteRule ^(.+)$ http://%{HTTP_HOST}/en/$1 [L,R,QSA] 

回答

0

使用RewriteCond来寻找2个字母郎代码的URI的开头:

RewriteEngine On 

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
# If the URL doesn't match /xx/otherstuff 
RewriteCond %{REQUEST_URI} !^([a-z]{2}/)(.*)$ 
# Rewrite to /en/ 
RewriteRule ^(.+)$ http://%{HTTP_HOST}/en/$1 [L,R,QSA] 

如果使用超过2级字符的代码郎一样,最多4个,使用[a-z]{2,4}代替。

+0

迈克尔 - 我试过你的解决方案。我得到了“http:// localhost/C:/xampp/htdocs/examples/MVC/en/index.php?url=index” – 2012-02-22 02:01:02

+0

@MustaphaGeorge请参阅上面的修改,添加'http:// $ {HTTP_HOST}' – 2012-02-22 02:04:07

+0

仍然不工作。时间到RTFM。 – 2012-02-22 02:33:50