When users request /
, I want to redirect them to /en
or /de
, depending on their preference specified in the HTTP request header Accept-Language
.
I guess this is easy with server-side scripting, but I need a .htaccess
solution as it has to work for a static site.
What I tried:
- mod_negotiation (either with a type map or with the
MultiViews
option):
Users get their preferred language, but they don’t get redirected.
- mod_rewrite (
RewriteCond %{HTTP:Accept-Language}
):
Users get redirected, but they don’t (necessarily ‡) get their preferred language.
(‡ Neither does it assure that the language has a quality value greater than 0, nor does it find the preferred language in case both languages are specified with different quality values.)
Is there a solution for this?
Whether making content negotiation redirect somehow, or allowing to check/compare quality values in the RewriteCond
directive, or something totally different.
Some thoughts:
If you have access to server configuration, there may be a way : the use of the RewriteMap directive in your server config.
You can then send the
Accept-Language
header to a Perl or whatever script, that will send back the preferred language that you can use in your RewriteRule with a 301.If you have access to a language like
php
, you can use a index.php file in "/
" that will send out the redirect with functionheader('Location: /en/static-pages.html')
. From php 5.3 there is also the functionlocale_accept_from_http()
, which returns the prefered locale from the header.But important : you want users to
"get their preferred language"
. Are you sure this technique makes the user get its preferred language? So many people do not set this in their browser preferences. The automatic language selection should (must?) be combined with the remembering of user’s choice, (cookie), and user’s choice should (must?) take precedence over automatic selection.Disclaimer: I have not tested this. I used something similar in the past for this type of logic, using mod_alias to set the variables and let mod_rewrite handle the multiple conditions. This gets easier in Apache 2.4 with If statements.
I should add that this example is using the apache config and not .htaccess. I remember there being some caveats around mod_rewrite in .htaccess, but I never use it due to the latency penalties. Good luck!