Anthony Faull
Anthony Faull

Reputation: 17957

Redirect based on Accept-Language

I need to honor the web browser's list of language preferences. Supported languages are English and French. For example: http_accept_language="jp-JP;fr;en-US;en" redirects to a directory called /French/. How can I do this with rewrite rules in my .htaccess file?

Upvotes: 3

Views: 698

Answers (2)

Nicolas Guérinet
Nicolas Guérinet

Reputation: 2226

I guess the goal would be to match with the first language in priority order set up in the browser. I guess the english version would be the default version and the french version for people living in Belgium, Canada, Switzerland. So, i would suggest to implement the following: It will return french if it finds french somewhere first in accept-language http field, then, it would look for english. Then, if there is neither english nor french, it would return the english version. I don't forget to exclude the robots.txt from the redirection as it should be in root folder of the website.

RewriteEngine On
#exclude robots.txt 
RewriteCond %{REQUEST_FILENAME} robots.txt
RewriteRule ^ - [L]
RewriteCond %{REQUEST_URI} ^/$
RewriteCond %{HTTP:Accept-Language} fr [NC]
RewriteRule ^$ https://nicolasgueri.net/fr/ [L,R=301]
RewriteCond %{HTTP:Accept-Language} en [NC]
RewriteRule ^$ https://nicolasgueri.net/en/ [L,R=301]
RewriteCond %{HTTP:Accept-Language} ^.*$ [NC]
RewriteRule ^$ https://nicolasgueri.net/en/ [L,R=301]

Upvotes: 0

Gumbo
Gumbo

Reputation: 655239

I wouldn’t use mod_rewrite for this but a more powerful language. Because Accept-Language is a list of weighted values (see quality value) and the occurrence of one of the identifiers does not mean that it’s preferred over another value (especially q=0 means not acceptable at all).

As already said, use a more powerful language than mod_rewrite, parse the list of value and find the best match of preferred options and available options.

Upvotes: 3

Related Questions