RewriteCond and rewriteRule to redirect depending on the domain

寵の児 提交于 2019-12-13 16:38:21

问题


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.



来源:https://stackoverflow.com/questions/37477953/rewritecond-and-rewriterule-to-redirect-depending-on-the-domain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!