Cloudflare Worker出现无限重定向问题,请求排查代码错误
问题分析与解决
你的极简代码本身逻辑无语法错误,但触发无限重定向的核心原因是:
- 当源站返回**重定向响应(301/302等)**时,你直接将该响应返回给客户端,客户端会发起新请求访问重定向目标;
- 如果重定向目标仍是当前绑定Worker的域名,新请求会再次触发Worker,Worker又去源站拿到相同的重定向响应,如此循环往复,形成无限重定向。
适配缓存需求的修正代码
如果你的目标是把响应缓存到Cloudflare Cache、仅缓存为空时访问源站,需要加入缓存逻辑,同时处理重定向避免循环:
addEventListener('fetch', event => { event.passThroughOnException() event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { // 先尝试从Cloudflare Cache读取响应 const cacheKey = new Request(request.url, { method: request.method, headers: request.headers }) const cache = caches.default let response = await cache.match(cacheKey) if (!response) { // 缓存为空时请求源站 response = await fetch(request) // 将源站响应存入缓存,这里设置1小时缓存有效期,可按需调整 const cacheableResponse = new Response(response.body, response) cacheableResponse.headers.set('Cache-Control', 'max-age=3600') event.waitUntil(cache.put(cacheKey, cacheableResponse.clone())) response = cacheableResponse } // 处理同域名重定向,避免循环 if (response.status >= 300 && response.status < 400) { const location = response.headers.get('Location') if (location && location.startsWith('/')) { // 将相对路径重定向转为绝对路径,避免客户端重复请求同域名 const absoluteLocation = new URL(location, request.url).href response = new Response(response.body, { status: response.status, headers: new Headers(response.headers) }) response.headers.set('Location', absoluteLocation) } } return response }
关键说明
- 缓存逻辑:通过
caches.default.match检查缓存,无缓存时请求源站并将响应存入Cache; - 重定向处理:把相对路径重定向转为绝对路径,避免客户端重复请求同域名触发Worker循环;
- 缓存规则:手动设置
Cache-Control头,确保响应能被Cloudflare Cache存储(默认重定向响应不会被缓存)。
内容的提问来源于stack exchange,提问作者jerry xu





