强制用户在URL中的语言首选项 - 重写?

时间:2012-02-19 20:54:02

标签: .htaccess mod-rewrite

我想在URL中指定用户的语言首选项。 是否可以使用.htaccess重写规则将一个段添加到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]

1 个答案:

答案 0 :(得分:0)

使用RewriteCond在URI的开头查找2个字母的lang代码:

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个字符的lang代码,例如最多4个,请改用[a-z]{2,4}