简体   繁体   中英

RewriteCond and rewriteRule to redirect depending on the domain

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM