How to redirect based on Accept-Language using Apache / mod_rewrite

To redirect languages, we are currently creating folders in the root directory of websites containing the index.php file, which checks the HTTP_ACCEPT_LANGUAGE server HTTP_ACCEPT_LANGUAGE . e.g. for URL www.example.com/press/

in /var/www/site/press/index.php :

 <?php if ($_SERVER["HTTP_ACCEPT_LANGUAGE"] == "en") header("location: ../press_en.php"); else header("location: ../press_de.php"); ?> 

As the site grows, we now have many such folders. I am trying to clear this by moving the redirects to a single .htaccess file:

 RewriteEngine on # Set the base path here RewriteBase /path/to/site/ # The 'Accept-Language' header starts with 'en' RewriteCond %{HTTP:Accept-Language} (^en) [NC] # EN redirects RewriteRule press(/?)$ press_en.php [L,R] # DE redirects (for all languages not EN) RewriteRule press(/?)$ press_de.php [L,R] 

The idea is the same as the php file, but it does not work. I tried all possible language settings / orders in Firefox settings and checked the headers were correct, but it always serves for the press_de.php file.

What am I doing wrong, or is there a better way? (not including content negotiation / multivisors or anything that requires renaming files, this is currently not an option).

+4
source share
2 answers

I would put a language indicator at the beginning of the url, like /en/… or /de/… Then you can use one script that checks the preferred language and redirects the request by adding a language indicator:

 // negotiate-language.php $availableLanguages = array('en', 'de'); if (!preg_match('~^/[az]{2}/~', $_SERVER['REQUEST_URI'])) { $preferedLanguage = someFunctionToDeterminThePreferedLanguage(); if (in_array($preferedLanguage, $availableLanguages)) { header('Location: http://example.com/'.$preferedLanguage.$_SERVER['REQUEST_URI']); } else { // language negotiation failed! header($_SERVER['SERVER_PROTOCOL'].' 300 Multiple Choices', true, 300); // send a document with a list of the available language representations of REQUEST_URI } exit; } 

And the relevant rules:

 RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^/]+)$ negotiate-language.php [L] RewriteRule ^([az]{2})/([^/]+)$ $2_$1.php [L] 

Please note that you need the correct function someFunctionToDeterminThePreferedLanguage as the Accept-Language header field - this is not a single value, but a list of qualified values. Thus, there may be more than one value, and the first value is not always the preferred value.

+6
source

in htaccess

 RewriteEngine on RewriteCond %{HTTP:Accept-Language} (en) [NC] RewriteRule .* server.com/press_en.php [L] RewriteCond %{HTTP:Accept-Language} (de) [NC] RewriteRule .* server.com/press_de.php [L] 
+2
source

All Articles