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

PHP如何根据查询字符串重定向并移除target(含大小写)参数

解决PHP重定向时自动附加target=部分的问题

你的问题出在直接使用$_SERVER['QUERY_STRING']作为重定向目标,它会把整个查询字符串(比如target=someurl.html)拼接到URL后,导致出现target=/someurl.html的错误路径。要实现不带target=的重定向,核心是提取target参数(兼容大小写)对应的值,再用这个值作为重定向目标。

方案一:遍历GET参数兼容大小写

这种方式通过遍历所有GET参数,将键名转为小写后匹配target,能可靠获取目标URL:

<?php
$targetUrl = '';

// 遍历GET参数,兼容target/TARGET大小写
foreach ($_GET as $key => $value) {
    if (strtolower($key) === 'target') {
        $targetUrl = $value;
        break;
    }
}

if (!empty($targetUrl)) {
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: " . $targetUrl);
} else {
    // 无target参数时的默认跳转,可根据需求修改
    header("Location: /");
}
exit;
?>

方案二:正则提取目标URL

如果查询字符串结构简单,也可以用正则直接从$_SERVER['QUERY_STRING']中提取target参数的值:

<?php
// 匹配target或TARGET开头的参数值,忽略大小写
preg_match('/(?:target)=([^&]+)/i', $_SERVER['QUERY_STRING'], $matches);
$targetUrl = $matches[1] ?? '';

if (!empty($targetUrl)) {
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: " . $targetUrl);
} else {
    header("Location: /");
}
exit;
?>

注意事项

  • 若target参数的值是相对路径(如someurl.html),重定向后会基于当前域名跳转;如果是绝对URL(如https://example.com/page.html)则直接跳转到对应地址。
  • 为避免开放重定向漏洞,建议对$targetUrl做合法性验证,比如限制只能跳转到本站域名下的地址,或者加入白名单。

内容的提问来源于stack exchange,提问作者Flakes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 14:01:16