заставить язык пользователя в URL - rewriterule? - PullRequest
1 голос
/ 20 февраля 2012

Я хочу указать языковые предпочтения пользователя в 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

Если язык отсутствует, я хочу автоматическипреобразовать URL-адрес по умолчанию в английский язык.

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 голосов
/ 20 февраля 2012

Используйте RewriteCond, чтобы найти двухбуквенный код языка в начале 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}.

...