RewriteCond and rewriteRule to redirect depending

2019-07-18 23:40发布

问题:

First of all, I've got a few domains pointing to the same webpage, each domain corresponfing to a different language. The webpage (Drupal) identifies the language using a /lang parameter in the url (example.com/en). I need to redirect every domain to its corresponding language so I need something like:

  • example.com -> example.com/en
  • example.ru -> example.ru/ru
  • example.fr -> example.fr/fr

I defined some rules in htaccess but they don't do what i expected:

# Rewrite --- http://www.example.com => http://www.example.com/en
RewriteCond %{HTTP_HOST}   !^www\.example\.com [NC]
RewriteRule ^$ /en? [L,R=301]

# Rewrite --- http://www.example.ru => http://www.example.ru/ru
RewriteCond %{HTTP_HOST}   !^www\.example\.ru [NC]
RewriteRule ^$ /ru? [L,R=301]

Instead of changing example.com to example.com/en and example.ru to example.ru/ru it appends /en to all domains. Is it something I am missing?

Any advice would be very helpful.

回答1:

This should work:

# Rewrite --- http://www.example.com => http://www.example.com/en
RewriteCond %{HTTP_HOST}   ^www\.example\.com [NC]
RewriteCond %{REQUEST_URI}  !^/en(/(.*)$|$)
RewriteRule ^ /en%{REQUEST_URI} [L,R=301]

# Rewrite --- http://www.example.ru => http://www.example.ru/ru
RewriteCond %{HTTP_HOST}   ^www\.example\.ru [NC]
RewriteCond %{REQUEST_URI}  !^/ru(/(.*)$|$)
RewriteRule ^ /ru%{REQUEST_URI} [L,R=301]

You can remove ,R=301 if you want to make the rewrite invisible to the user.



回答2:

You can use these rules :

RewriteEngine on
# example.com to example.com/en
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteRule ^((?!en).*)$ /en/$1 [L,R]
# example.ru|fr to example.com/ru|fr
RewriteCond %{HTTP_HOST} ^(?:www\.)?.+\.(ru|fr)$
RewriteRule ^((?!ru|fr).*)$ /%1/$1 [L,R]

Just replace the "example.com" with "youdomain.com" in the first RewriteCondition.