简体   繁体   English

RewriteCond和rewriteRule根据域进行重定向

[英]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 ). 网页(Drupal)使用URL( example.com/en )中的/lang参数标识语言。 I need to redirect every domain to its corresponding language so I need something like: 我需要将每个域重定向到其对应的语言,所以我需要类似以下内容:

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

I defined some rules in htaccess but they don't do what i expected: 我在htaccess中定义了一些规则,但是它们没有达到我的期望:

# 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. 相反,改变example.comexample.com/enexample.ruexample.ru/ru其追加/en到所有领域。 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. 如果要使重写对用户不可见,可以删除,R=301

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. 只需在第一个RewriteCondition中将“ example.com”替换为“ youdomain.com”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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