如何根据接受语言与Apache / mod_rewrite的重定向 [英] How to redirect based on Accept-Language with Apache / mod_rewrite
问题描述
有关的语言重定向我们现在创建一个包含哪些检查 HTTP_ACCEPT_LANG
服务器变量的index.php文件夹中的Web根。例如为网址 www.example.com/$p$pss /
For language redirects we currently create folders in the web root containing an index.php file which checks the HTTP_ACCEPT_LANG
server variable. e.g. for the url www.example.com/press/
在 /var/www/site/$p$pss/index.php
:
<?php
if ($_SERVER["HTTP_ACCEPT_LANGUAGE"] == "en")
header("location: ../press_en.php");
else
header("location: ../press_de.php");
?>
随着网站的不断壮大,我们现在有很多这样的文件夹。我试图通过将重定向到一个.htaccess文件来打扫一下:
As the site has grown, we now have many such folders. I am trying to clean this up 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]
我们的想法是一样的PHP文件,但它不工作。我已经尝试了所有可能的语言设置/ Firefox中preferences订单,并检查了头部是正确的,但它总是服务于 press_de.php
文件。
我是什么做错了,或者有更好的办法吗? (不包括内容协商/多视图或任何需要重命名文件,这目前还不是一个选项)的。
What am I doing wrong, or is there a better way? (not including content negotiation / multiviews or anything that requires renaming files, this is not currently an option).
推荐答案
我会把语言指示器在URL路径的开始像 / EN / ...
或 /德/ ...
。然后,你可以使用检查preferred语言和重定向由prepending语言指示请求一个脚本:
I would put the language indicator at the start of the URL path like /en/…
or /de/…
. Then you can use a single script that checks the preferred language and redirects the request by prepending the language indicator:
// negotiate-language.php
$availableLanguages = array('en', 'de');
if (!preg_match('~^/[a-z]{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;
}
和相应的规则:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)$ negotiate-language.php [L]
RewriteRule ^([a-z]{2})/([^/]+)$ $2_$1.php [L]
请注意,你需要一个合适的 someFunctionToDeterminThe preferedLanguage
函数的 接受语言的报头字段是不是一个单一的值,但合格值的列表。所以可能有不止一个值和所述第一值并不总是prefered值
Note that you need a proper someFunctionToDeterminThePreferedLanguage
function as Accept-Language header field is not a single value but a list of qualified values. So there might be more than just one value and the first value is not always the prefered value.
这篇关于如何根据接受语言与Apache / mod_rewrite的重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!