問題描述
對于語言重定向,我們目前在 Web 根目錄中創建文件夾,其中包含檢查 HTTP_ACCEPT_LANGUAGE
服務器變量的 index.php 文件.例如對于網址 www.example.com/press/
For language redirects we currently create folders in the web root containing an index.php file which checks the HTTP_ACCEPT_LANGUAGE
server variable. e.g. for the url www.example.com/press/
在/var/www/site/press/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 首選項中嘗試了所有可能的語言設置/順序,并檢查了標題是否正確,但它始終為 press_de.php
文件提供服務.
The idea is the same as the php file, but it doesn't work. I have tried all the possible language settings / orders in Firefox preferences, and checked the headers are correct, but it always serves the press_de.php
file.
我做錯了什么,還是有更好的方法?(不包括內容協商/多視圖或任何需要重命名文件的內容,目前這不是一個選項).
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/...
或 /de/...代碼>.然后,您可以使用單個腳本來檢查首選語言并通過添加語言指示符來重定向請求:
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]
請注意,您需要一個正確的 someFunctionToDeterminThePreferedLanguage
函數作為 Accept-Language 標頭字段 不是單個值,而是限定值的列表.所以可能有多個值,第一個值并不總是首選值.
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 基于 Accept-Language 重定向的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!