开发者

Language Redirect with mod_rewrite

开发者 https://www.devze.com 2023-03-09 07:32 出处:网络
I have a site that is offered开发者_C百科 in 7 languages. I want to be able to redirect the user based on the browser language only when the user is visiting the homepage. This is meant for added us

I have a site that is offered开发者_C百科 in 7 languages.

I want to be able to redirect the user based on the browser language only when the user is visiting the homepage. This is meant for added usability when it comes to organic traffic. I need this redirect to only apply to the homepage as the site also sends out mailers specific to each language and they will not work if a user is redirected.

Also each language is a sub-domain. i.e. www.site.com for English and de.site.com for German. Mailer URL's would look similar to: www.site.com/home/login?query=string

I'd like to do this with an .htaccess file if possible.

Can anyone offer insight?

Thanks.


Since you only want to redirect while on your homepage , you can do like this (assumging www.xyz.com is your home page)

RewriteCond %{HTTP:HOST} www.xyz.com  // user visiting default
RewriteCond %{HTTP:Accept-Language} ^de [NC] // browser language German
RewriteRule ^$ de.xyz.com [L,R=301] // R=302 if you need temporary redirect

http://tech-blog.borychowski.com/index.php/2009/03/htaccess/redirect-according-to-browser-language-mod-rewrite-and-http_accept_language/


This is an elaboration on Rizwan's answer, too much for an edit or comment (I tried).

I assume you only want to redirect when the user visits the homepage of your default domain (here of www.xyz.com, not of de.xyz.com etc.). Here's how you can do it (following these instructions):

RewriteCond %{HTTP:HOST} www.xyz.com         // Visit to default domain.
RewriteCond %{HTTP:Accept-Language} ^de [NC] // Browser language German.
RewriteRule ^$ http://de.xyz.com/       [L,R=301]

RewriteCond %{HTTP:HOST} www.xyz.com
RewriteCond %{HTTP:Accept-Language} ^it [NC]
RewriteRule ^$ http://it.xyz.com/       [L,R=301]

# etc. for your other 5 languages

Notes & Explanations:

  • R=301 is a permanent redirect, which will normally be cached by browsers. This limits your options of changing the redirect target later, so you might consider using a non-cached R=302 temporary redirect instead.
  • Determining the preferred language by looking at the first value in the Accept-Language: header will work in most cases, but is not according to the standard. It misinterprets theoretically possible values like de;q=0.5, en;q=0.9. To get this perfectly right, see inspirations here and here.
  • In RewriteRule, ^$ matches the empty string, which means, "the homepage". That's because Apache will remove the directory prefix from the file path that corresponds to the directory your .htaccess is found in [source]. (In VirtualHost context, removing that / does not happen and the pattern would have to be ^/$ instead.)
0

精彩评论

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

关注公众号