Cloudflare Workers自制HTTP代理无法处理相对重定向求解决方案
解决Cloudflare Workers HTTP代理的相对重定向问题
问题分析
当前代理逻辑中,当目标服务器返回相对重定向(比如Location: /relative-redirect/1)时,浏览器会基于代理域名(https://<domain>.workers.dev)拼接新URL,生成无效的https://<domain>.workers.dev/relative-redirect/1,而非正确的https://<domain>.workers.dev/https://httpbin.dev/relative-redirect/1。
绝对重定向能正常工作,是因为目标返回的是完整URL,浏览器会直接将其作为代理路径的后缀使用。
解决方案
需要在代理响应返回前,拦截并修正Location头,把相对路径转换为带原目标前缀的代理格式URL:
export default { async fetch(request, env, ctx): Promise<Response> { const { search, pathname } = new URL(request.url); const url = pathname.slice(1); if (!url) { return new Response("Please specify a target URL.", { status: 400 }); } let targetURL; try { targetURL = new URL(url); } catch { return new Response("Invalid URL.", { status: 400 }); } const forwardedRequest = new Request(targetURL, request); const res = await fetch(forwardedRequest); const response = new Response(res.body, res); // 处理相对重定向的核心逻辑 const location = response.headers.get('Location'); if (location) { let newLocation; // 判断是否为相对路径 if (!location.startsWith('http://') && !location.startsWith('https://')) { // 基于原目标URL生成完整绝对路径 newLocation = new URL(location, targetURL).href; } else { newLocation = location; } // 替换Location头为代理格式的URL response.headers.set('Location', `/${newLocation}`); } return response; }, } satisfies ExportedHandler<Env>;
逻辑说明
- 检测响应中的
Location头,若存在则进入处理流程 - 区分相对/绝对路径:相对路径不会以
http开头,需要用原targetURL作为基准解析成完整URL - 将解析后的完整URL拼接到代理路径后(添加
/前缀),替换原Location头 - 浏览器收到修正后的
Location后,会请求正确的代理格式URL,代理即可正常转发到目标地址
内容的提问来源于stack exchange,提问作者ADrakkar
相关产品推荐
相关产品推荐

