如何自动为网站外部URL添加商户联盟标识符 求JS/PHP实现方案
解决方案
原代码存在的问题
- 逻辑判断写反:
indexOf < 0代表链接不包含对应域名,原代码反而执行加前缀操作,完全不符合需求 - 语法错误:
adairs.com.au未加引号,affiliateURL变量未定义 - 方法废弃:使用了已被标准废弃的
escape方法做URL编码,易出现编码异常 - 扩展性差:每新增一个商户就要单独定义变量、新增判断分支,维护成本高
修复后可直接运行的JavaScript实现
采用配置对象统一管理商户联盟规则,新增商户仅需在配置中添加一行键值对,无需修改逻辑代码:
// 商户联盟配置,新增商户直接添加「域名: 联盟前缀」格式的键值对即可 const affiliateConfig = { 'adairs.com.au': 'https://t.example.com/12345/t/54321?Url=', 'bedthreads.com.au': 'https://t.example.com/12121/t/21212?Url=' }; // 绑定所有a标签点击事件 $('a').on('click', function() { const originalHref = this.href; // 跳过已添加过联盟前缀的链接 for (const prefix of Object.values(affiliateConfig)) { if (originalHref.startsWith(prefix)) return true; } // 解析链接域名,非标准链接直接跳过 let urlObj; try { urlObj = new URL(originalHref); } catch (e) { return true; } // 匹配对应商户规则添加前缀 for (const [domain, prefix] of Object.entries(affiliateConfig)) { if (urlObj.hostname.endsWith(domain)) { this.href = prefix + encodeURIComponent(originalHref); // 调试用,上线可删除下方alert alert(this.href); return true; } } // 未匹配到规则的链接直接跳转 return true; });
注:本代码依赖jQuery,若无需依赖jQuery可将事件绑定部分替换为原生
document.querySelectorAll('a').forEach()写法。
PHP实现方案
该需求完全可以通过PHP实现,服务端渲染阶段直接替换链接,无需依赖客户端JavaScript执行,对搜索引擎爬虫更友好:
<?php // 商户联盟配置,新增商户直接添加「域名: 联盟前缀」格式的键值对即可 $affiliateConfig = [ 'adairs.com.au' => 'https://t.example.com/12345/t/54321?Url=', 'bedthreads.com.au' => 'https://t.example.com/12121/t/21212?Url=' ]; function addAffiliateLinks(string $htmlContent, array $affiliateConfig): string { $dom = new DOMDocument(); // 处理中文编码适配问题 libxml_use_internal_errors(true); $dom->loadHTML('<?xml encoding="utf-8" ?>' . $htmlContent); libxml_clear_errors(); $xpath = new DOMXPath($dom); $links = $xpath->query('//a[@href]'); foreach ($links as $link) { $originalHref = $link->getAttribute('href'); // 跳过已添加过联盟前缀的链接 $hasProcessed = false; foreach ($affiliateConfig as $prefix) { // PHP8.0以下版本可替换为 strpos($originalHref, $prefix) === 0 if (str_starts_with($originalHref, $prefix)) { $hasProcessed = true; break; } } if ($hasProcessed) continue; $urlInfo = parse_url($originalHref); if (!isset($urlInfo['host'])) continue; // 匹配对应商户规则添加前缀 foreach ($affiliateConfig as $domain => $prefix) { // PHP8.0以下版本可替换为 substr($urlInfo['host'], -strlen($domain)) === $domain if (str_ends_with($urlInfo['host'], $domain)) { $newHref = $prefix . rawurlencode($originalHref); $link->setAttribute('href', $newHref); break; } } } return $dom->saveHTML(); } // 使用示例 $originalPageContent = '你的页面原始HTML内容'; $processedContent = addAffiliateLinks($originalPageContent, $affiliateConfig); echo $processedContent; ?>
内容的提问来源于stack exchange,提问作者KaiH
相关产品推荐
相关产品推荐

