← 中文资源

简体中文版本

面向缓存键的 URL 规范化

把 URL 规范化为缓存键:协议主机小写、去默认端口、查询参数排序、去除 fragment。

阅读英文原文

目标

按四条规则规范化每个 URL:scheme 与 host 转小写、删除默认端口(http 80 / https 443)、查询参数按键再按值排序、丢弃 fragment。按输入顺序输出规范化字符串。

要点

用 URL 构造器解析,其结构化访问器可直接取 host、port、path 与参数;参数收集后按 (key, value) 排序再拼接;空 pathname 渲染为单个斜杠。

提示

路径和查询转小写会破坏大小写敏感资源;仅按整串排序参数时 b=2 会错排到 a=9 前。

验证

运行两个样例:默认端口去除、重复键按值排序、fragment 丢弃、空路径补斜杠各自生效;含大写字母的路径必须原样保留。 公开样例(与参考实现实测一致):

  • 输入 {"urls":["HTTP://Example.COM:80/a/b?b=2&a=1#frag","https://example.com:443/a/b/?z=1","http://example.com:8080/x?k=2&k=1"]},期望 {"normalized":["http://example.com/a/b?a=1&b=2","https://example.com/a/b/?z=1","http://example.com:8080/x?k=1&k=2"]}。
  • 输入 {"urls":["http://example.com/#top","http://example.com"]},期望 {"normalized":["http://example.com/","http://example.com/"]}。

代码示例

function normalizeUrl(raw) {
  const u = new URL(raw);
  const host = u.hostname.toLowerCase();
  let port = '';
  if (u.port && !((u.protocol === 'http:' && u.port === '80') || (u.protocol === 'https:' && u.port === '443'))) {
    port = ':' + u.port;
  }
  const pairs = Array.from(u.searchParams.entries());
  pairs.sort((x, y) => (x[0] === y[0] ? (x[1] < y[1] ? -1 : 1) : x[0] < y[0] ? -1 : 1));
  const search = pairs.map((p) => p[0] + '=' + p[1]).join('&');
  let path = u.pathname;
  if (path === '') path = '/';
  return u.protocol + '//' + host + port + path + (search ? '?' + search : '');
}

const payload = JSON.parse(input);
console.log(JSON.stringify({ normalized: payload.urls.map(normalizeUrl) }));