You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP浏览器语言检测重定向触发ERR_TOO_MANY_REDIRECTS问题求助

解决浏览器语言检测导致的循环重定向问题

问题说明

我有一段PHP代码,用于检测浏览器语言并将用户重定向到对应语言版本的网站。若对应版本不存在,则重定向至英文版本。主语言为西班牙语,对应路径是https://example.com/。问题在于,当用户浏览器语言为西班牙语时,代码会将用户重定向到相同路径,从而引发ERR_TOO_MANY_REDIRECTS错误。目前代码对英文和葡萄牙语的重定向功能正常,曾尝试使用return false,但页面会变成空白。

原代码

<?php
$accept_languaje = !empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : 'es';
$main_languaje   = substr($accept_languaje, 0, 2);
switch ($main_languaje):
    case 'es':
        exit(header("Location: https://example.com/"));
    case 'en':
        exit(header("Location: https://example.com/en.php"));
    case 'pt':
        exit(header("Location: https://example.com/pt.php"));
endswitch;
if (false !== strpos($accept_languaje, 'es')) {
    exit(header("Location: https://example.com/"));
}
if (false !== strpos($accept_languaje, 'en')) {
    exit(header("Location: https://example.com/en.php"));
}
if (false !== strpos($accept_languaje, 'pt')) {
    exit(header("Location: https://example.com/pt.php"));
}
exit(header("Location: https://example.com/en.php"));
?>

修改后的代码(简洁版)

<?php
$accept_language = !empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : 'es';
$main_language   = substr($accept_language, 0, 2);

// 仅当当前不在西班牙语根页面时,才执行重定向逻辑
if ($_SERVER['REQUEST_URI'] !== '/') {
    switch ($main_language):
        case 'es':
            header("Location: https://example.com/");
            exit;
        case 'en':
            header("Location: https://example.com/en.php");
            exit;
        case 'pt':
            header("Location: https://example.com/pt.php");
            exit;
    endswitch;

    // 处理带区域的语言标识(如es-ES、en-US)
    if (strpos($accept_language, 'es') !== false) {
        header("Location: https://example.com/");
        exit;
    } elseif (strpos($accept_language, 'en') !== false) {
        header("Location: https://example.com/en.php");
        exit;
    } elseif (strpos($accept_language, 'pt') !== false) {
        header("Location: https://example.com/pt.php");
        exit;
    }

    // 默认重定向到英文版本
    header("Location: https://example.com/en.php");
    exit;
}
?>

修改要点

  1. 增加当前页面判断:通过$_SERVER['REQUEST_URI'] !== '/'检查用户是否已经在西班牙语根页面,若是则直接跳过所有重定向逻辑,避免循环。
  2. 修正变量拼写:将accept_languaje改为符合规范的accept_language。
  3. 优化判断逻辑:把多个独立if改为elseif,减少不必要的条件检查。
  4. 规范语法:将exit(header(...))拆分为header()后单独exit,逻辑更清晰。

内容的提问来源于stack exchange,提问作者Sergio Yael A.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 15:09:12