背景与价值


URL规范化可减少重复与绕过路径。结合Canonical与301治理,可实现一致入口与安全外跳。


统一规范


  • 规范化:统一结尾斜杠与大小写;移除冗余参数。
  • Canonical:向页面下发canonical标签指向唯一URL。
  • 301策略:非规范URL重定向到规范入口。

核心实现


规范化与重定向


function normalize(u: URL): URL { const x = new URL(u.href); x.pathname = x.pathname.replace(/\/+$/,''); x.pathname = x.pathname.toLowerCase(); x.searchParams.sort(); return x }

type Res = { status: (n: number) => Res; setHeader: (k: string, v: string) => void; end: (b?: string) => void }

function redirectIfNeeded(current: URL, res: Res): boolean { const norm = normalize(current); if (norm.href !== current.href) { res.status(301).setHeader('Location', norm.href).end(); return true } return false }

function canonicalTag(norm: URL): string { return `<link rel="canonical" href="${norm.href}">` }

落地建议


  • 在路由层统一规范化与重定向,并在页面注入canonical标签,避免重复与绕过。

验证清单


  • 非规范URL是否301到规范入口;页面是否下发canonical标签。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部