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

PHP基于URL参数的重定向如何支持正则/通配符匹配

调整重定向规则配置

正则规则统一用~作为定界符(避免和URL里的/冲突无需转义),目标地址用$1/$2这类占位符对应正则捕获组即可,原有精确匹配规则可以保留无需修改:

$domain = 'https://你的目标域名.tld';
$redirects = [
    // 原有精确匹配规则正常生效
    'request' => "$domain/dest",
    'request2' => "$domain/dest2",
    'request3' => "$domain/dest3",
    // 新增正则匹配规则,匹配所有pics/开头的路径
    '~^pics/(.*)$~' => "$domain/pictures/$1",
    // 更多正则规则示例:匹配request/开头的所有路径
    '~^request/(.*)$~' => "$domain/destination/$1",
];

修改跳转处理逻辑

先判断是否命中精确匹配(性能更高),未命中则遍历正则规则逐一匹配,匹配成功后用preg_replace替换出最终跳转地址:

if (isset($_GET['req'])) {
    $reqPath = trim($_GET['req'], '/');
    // 优先走精确匹配
    if (isset($redirects[$reqPath])) {
        $loc = htmlspecialchars($redirects[$reqPath]);
        header("Location: " . $loc);
        exit();
    }
    // 精确匹配未命中,遍历正则规则匹配
    foreach ($redirects as $pattern => $target) {
        // 仅处理我们约定的以~开头和结尾的正则规则
        if (str_starts_with($pattern, '~') && str_ends_with($pattern, '~')) {
            if (preg_match($pattern, $reqPath)) {
                $loc = htmlspecialchars(preg_replace($pattern, $target, $reqPath));
                header("Location: " . $loc);
                exit();
            }
        }
    }
}
// 所有规则都未命中,跳转至首页
header("Location: $domain");
exit();

补充说明

  • 若使用的PHP版本低于8.0,没有内置str_starts_with和str_ends_with函数,可以用substr替代判断:
    str_starts_with($pattern, '~') 替换为 substr($pattern, 0, 1) === '~'
    str_ends_with($pattern, '~') 替换为 substr($pattern, -1) === '~'
  • 正则规则建议加^和$限定匹配起止位置,避免意外命中不相关路径
  • 如需设置永久重定向(利于SEO),可以修改header语句为 header("Location: " . $loc, true, 301);

内容的提问来源于stack exchange,提问作者Jase Wolf - theythem

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 18:54:04