问题
I want to specify the user's language preference in the URL. Is it possible to use .htaccess rewrite rule to add a segment to the url, if missing.
URL should normally have this structure
mysite.com/directory/en
mysite.com/directory/fr
mysite.com/directory/en/about_us.php
mysite.com/directory/fr/about_us.php
If language is missing, I want to automatically transform the url to default to english language.
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
Example:
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]
***** one day later **********
can someone help me understand exactly what Michael's solution is doing and how to change htaccess if I move to new subdirectory
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:
Use a RewriteCond
to look for the 2 letter lang code at the beginning of the 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]
If you are using more than 2 character lang codes, like up to 4, use [a-z]{2,4}
instead.
来源:https://stackoverflow.com/questions/9353124/force-users-language-preference-in-the-url-rewriterule