模仿 Google 首頁自動語言導向機制,利用瀏覽器送出的 Accept-Language 標頭,讓使用者無需手動選擇即可進入對應語系頁面。
瀏覽器在 HTTP 請求標頭中包含 Accept-Language,格式如:
zh-cnzh-cn,en;q=0.8,ko;q=0.5,zh-tw;q=0.3PHP 可透過 $_SERVER['HTTP_ACCEPT_LANGUAGE'] 取得。
<?php
error_reporting(E_ALL & ~E_NOTICE);
// 取得第一優先語系(簡易版,僅解析第一個代碼)
if (preg_match('/^([a-z\-]+)/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches)) {
$lang = strtolower($matches[1]);
} else {
$lang = 'en'; // 預設英文
}
// 導向對應站台
switch ($lang) {
case 'zh-cn':
header('Location: https://cn.example.com/');
break;
case 'zh-tw':
case 'zh-hk':
header('Location: https://tw.example.com/');
break;
case 'ko':
header('Location: https://ko.example.com/');
break;
case 'ja':
header('Location: https://jp.example.com/');
break;
default:
header('Location: https://en.example.com/');
}
exit;
?>
function parseAcceptLanguage($header) {
$langs = [];
foreach (explode(',', $header) as $part) {
$part = trim($part);
if (preg_match('/^([a-z\-]+)(?:;q=([0-9.]+))?$/i', $part, $m)) {
$langs[$m[1]] = isset($m[2]) ? (float)$m[2] : 1.0;
}
}
arsort($langs); // 依優先權遞減排序
return $langs;
}
$langs = parseAcceptLanguage($_SERVER['HTTP_ACCEPT_LANGUAGE']);
// 依序嘗試匹配支援的語系
$supported = ['zh-cn', 'zh-tw', 'en', 'ja', 'ko'];
foreach ($langs as $lang => $q) {
if (in_array($lang, $supported)) {
header("Location: https://{$lang}.example.com/");
exit;
}
}
// 都不匹配則導向預設
header('Location: https://en.example.com/');
header()Accept-Language,需有預設導向