搜索词含pc时跳转至其他站点并移除pc关键词的实现方案
PC关键词搜索请求重定向实现方案
下面给出两种主流场景的实现方式,可根据自己的部署环境选择:
方案1:Nginx 配置实现(性能最优)
直接在站点配置中添加重写规则,无需改动业务代码:
server { listen 80; server_name www.somesite.com; # 匹配s参数前缀为pc的请求,若需匹配任意位置含pc可调整正则规则 if ($arg_s ~* ^pc(.*)$) { # 过滤原请求参数中的s字段,保留其余参数 set $filtered_args $args; if ($filtered_args ~* "(^|&)s=[^&]*(&|$)") { set $filtered_args $1$3; } # 302为临时重定向,需要永久重定向可改为301 return 302 https://sub.somesite.com/index.php?p=$1$filtered_args; } # 其余原有配置保持不变 }
方案2:PHP 代码实现(无服务器配置权限时使用)
在站点入口文件最顶部添加以下逻辑:
<?php $sVal = $_GET['s'] ?? ''; // 匹配s参数前缀为pc的场景,若需任意位置包含pc可改为 stripos($sVal, 'pc') !== false if (stripos($sVal, 'pc') === 0) { // 移除pc前缀,若需删除所有pc字符可改为 $pVal = str_ireplace('pc', '', $sVal) $pVal = substr($sVal, 2); // 移除原参数中的s字段 unset($_GET['s']); $extraQuery = http_build_query($_GET); $targetUrl = "https://sub.somesite.com/index.php?p=" . urlencode($pVal); if ($extraQuery) { $targetUrl .= "&" . $extraQuery; } header("Location: {$targetUrl}", true, 302); exit; } // 原有业务代码继续执行
注意事项
- 上述规则默认不区分大小写匹配pc字符,需要严格区分大小写的话把正则的
~*改成~,stripos改成strpos、str_ireplace改成str_replace即可 - 生产环境验证规则生效后,可将302临时重定向改为301永久重定向,利于搜索引擎收录
内容的提问来源于stack exchange,提问作者matthew Greenwood
相关产品推荐
相关产品推荐

