Change domain depending on url path

2019-07-24 22:08发布

问题:

I've got a multilingual website that works within different domains deppending on the language. All the domains share the same font code and the website (Drupal) determines the language using the path. Right now I've configured each domain to be redirected to its own language, so I've got:

  • www.example.com -> www.example.com/en
  • www.example.es -> www.example.es/es
  • www.example.ru -> www.example.ru/ru

This way, when an user enters the website the cms will switch the language to the one corresponding to that domain.

My problem is that when someone uses the language switcher on the website, it changes all the query parameters to show the content corresponding to that language but does not change the domain so, if I'm in www.example.com/en/something and switch to spanish I will end in www.example.com/es/algo.

I'd need de domain to change also according to the language (which will always be written like /en, /es, /ru just after the domain name) and, if possible, keep the query parameters.

I've written this code in the htaccess (for russian only, as a test) but I fear It may be totally wrong since it does nothing:

  RewriteCond %{REQUEST_URI}  ^/ru$1
  RewriteRule ^$1 http://www.example.ru/ru$1 [L,R=301]

Any advice would ve very helpful.

回答1:

Put these before your previous rules:

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

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

...

Be aware that this way, if for example user enters www.example.ru/en/something, the /en in path will be more important than .ru in hostname, thus resulting in redirect to www.example.com/en/something



回答2:

mod_rewrite uses regular expression. $1 referes to a group which needs to be "defined" in the match part (using the parenthesis and the . as "match all" operator):

RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^ru(.*)$ http://www.example.ru/$1 [L,R=301]