通过 cloudflare worker 使用相同的 URL 服务不同的缓存版本

Serve different cache versions using the same URL through cloudflare worker

我从许多使用不同版本的移动和桌面网站的人那里看到了一个非常普遍的问题,许多主题都具有此功能。问题是无论用户设备如何,Cloudflare 都会缓存相同的页面,从而导致桌面和移动版本之间的混合和不一致。

最常见的解决方案是将移动版本分成另一个 URL,但就我而言,我想使用相同的 URL 并使 Cloudflare 缓存同时适用于桌面和移动设备.

我发现 this 非常好的指南显示了如何解决这个问题,但是,工作代码似乎已经过时,我必须修改一些部分才能使其工作。

我为我的员工创建了一个新的子域,然后将路由分配到我的站点,因此它开始 运行。

worker 正在缓存所有内容,但是,它没有根据设备具有不同缓存版本的所需功能。

async function run(event) {
  const { request } = event;

  const cache = caches.default;

  // Read the user agent of the request
  const ua = request.headers.get('user-agent');
  let uaValue;


  if (ua.match(/mobile/i)) {
    uaValue = 'mobile';
  } else {
    uaValue = 'desktop';
  }

  console.log(uaValue);

  // Construct a new response object which distinguishes the cache key by device
  // type.
  const url = new URL(request.url);
  url.searchParams.set('ua', uaValue);
  const newRequest = new Request(url, request);

  let response = await cache.match(newRequest);
  if (!response) {
    // Use the original request object when fetching the response from the
    // server to avoid passing on the query parameters to our backend.
    response = await fetch(request, { cf: { cacheTtl: 14400 } });

    // Store the cached response with our extended query parameters.
    event.waitUntil(cache.put(newRequest, response.clone()));
  }

  return response;
}

addEventListener('fetch', (event) => {
  event.respondWith(run(event));
});

它确实在检测正确的用户代理,但它应该根据分配的查询字符串有两个独立的缓存版本...

我想也许我缺少一些配置,我不知道为什么它没有按预期工作。就像现在一样,我仍然混合了我的移动和桌面缓存版本。

这里的问题是 fetch() 本身已经进行了正常的缓存,独立于您对它周围的缓存 API 的使用。所以 fetch() 可能仍然 return 一个针对错误 UA 的缓存响应。

如果您可以让 back-end 忽略查询参数,那么您可以在传递给 fetch() 的请求中包含查询,以便它正确地以不同方式缓存两个结果。 (企业客户可以使用 custom cache keys 作为一种无需更改 URL 即可完成此操作的方法。)

如果这样做,那么您还可以删除 cache.match()cache.put() 调用,因为 fetch() 本身将处理缓存。