.htaccesshttp-accept-language

Redirect by Accept-Language header and preserve URL path


I'm reworking my website and I want Apache web server to redirect visitors like it's done on World of Tanks Europe website. For example, if I try to open URL https://worldoftanks.eu/news/, it would add en/ before news/ and open the page in English. What do I have now at my .htaccess file in root folder:

Options -Indexes
RewriteEngine on
# redirect to Russian section if the visitor has Russian language
RewriteCond %{HTTP:Accept-Language} ^ru [NC]
RewriteRule ^$ /ru/ [L,R=301]
# everyone else should be redirected to the English section
RewriteRule ^$ /en/ [L,R=301]

But this is valid only if the visitor starts navigating from the website's home page. Any ideas?

UPD1: I have followed CBroe's recommendation he provided in comments and now I have something like this:

Options -Indexes
RewriteEngine on
# redirect to Russian section if the visitor has Russian language
RewriteCond %{HTTP:Accept-Language} ^(ru|be|uk|kk) [NC]
RewriteCond %{REQUEST_URI} !^/ru/.*$
RewriteRule (.*) /ru/$1 [L,R=301]
# everyone else should be redirected to the English section
RewriteCond %{REQUEST_URI} !^/en/.*$
RewriteRule (.*) /en/$1 [L,R=301]

As he mentioned, the bare line would cause an infinite redirect and it turned out like that, but resulted in http://example.com/en/ru/en/ru/en/ru/en/ru/en/ru/ redirect with respective error. The error occurs when I set Russian (or any of the languages in the condition) as the priority one, while English section works properly.

UPD2: I have tried the suggestion with !^/(ru|en)/ request URI rewrite condition, but it failed too. Maybe I put it in wrong section?

Options -Indexes
RewriteEngine on
# redirect to Russian section if the visitor has Russian (or any other CIS language) language
RewriteCond %{HTTP:Accept-Language} ^(ru|be|uk|kk) [NC]
RewriteCond %{REQUEST_URI} !^/(ru|en)/
RewriteRule (.*) /ru/$1 [L,R=301]

# everyone else should be redirected to the English section
RewriteCond %{REQUEST_URI} !^/en/.*$
RewriteRule (.*) /en/$1 [L,R=301]

Solution

  • @CBroe wins! His tip on putting the !^/(ru|en)/ condition both in "CIS languages" and "everything else" sections did the job.

    Options -Indexes
    RewriteEngine on
    # redirect to Russian section if the visitor has Russian language
    RewriteCond %{HTTP:Accept-Language} ^(ru|be|uk|kk) [NC]
    RewriteCond %{REQUEST_URI} !^/(ru|en)/
    RewriteRule (.*) /ru/$1 [L,R=301]
    
    # everyone else should be redirected to the English section
    RewriteCond %{REQUEST_URI} !^/(ru|en)/
    RewriteRule (.*) /en/$1 [L,R=301]