开发者

Multilanguage site, redirect based on cookie or accept-language (RewriteRule)

开发者 https://www.devze.com 2023-01-15 16:36 出处:网络
A few weeks ago i asked a question about a multilanguage site (see Multilanguage site, subdirectories as language (RewriteRule)).

A few weeks ago i asked a question about a multilanguage site (see Multilanguage site, subdirectories as language (RewriteRule)).

That works perfect (thanks for that) But since I want to make my website nicer and I started adding more languages a new problem showed up. I want to see if I can redirect users directly to the site in their language, if th开发者_StackOverflow中文版is language does not exists or a cookie is set I want to redirect users to their last language or my default language.

For now I created this part in my .htaccess

RewriteCond %{QUERY_STRING} ^$

RewriteRule ^/?$ en/ [L,R=301]

This causes that all calls to www.xxx.com/ are redirected to www.xxx.com/en/

Now the second part, in my php code I store a cookie this cookie is set for www.xxx.com/

I tried the following:

RewriteCond %{HTTP_COOKIE} language=([^;]+) [NC]
RewriteRule ^/?$ %1/ [L,R=302]

But this gives me an infinite loop.

I also tried this, so if my language is nl redirect to www.xxx.com/nl/ but this also results in an infinite loop. Also this code should only be executed in some cases

RewriteCond %{HTTP:Accept-Language} (nl) [NC]

RewriteRule ^/?$ nl/ [L,R=302]

Can someone help me and is this possible in an htaccess or should I create some logic in PHP?

1 Check if cookie is set with a language ( I guess this should be the above stated code)

 2a If a cookie is set redirect the user to that language

 2b If no cookie is set check the http-accept language

  2b1 If this language exists redirect to that language

  2b2 If that language does not exists redirect to the default

Thanks in advance


Accept-Language is a list of weighted language identifiers. Just the occurrence of a certain language identifier does not mean that it’s the most preferred language. There might be other languages that are more preferred (higher q value) or even not accepted at all (i.e. q=0).

So instead of just looking for a certain language identifier, parse the list of accepted languages and find the best match of accepted languages and available languages while considering the preference order. And since you seem to be using PHP, do that with PHP instead of mod_rewrite.

0

精彩评论

暂无评论...
验证码 换一张
取 消