export default { async fetch(request, env, ctx) { const url = new URL(request.url); // 默认代理的播放列表地址,也可以通过传入 ?url= 参数来代理其他地址 const targetUrlStr = url.searchParams.get('url') || "http://2.12356.xyz:8000/4.m3u"; if (!targetUrlStr) { return new Response("请提供需要代理的 url 参数", { status: 400 }); } let targetUrl; try { targetUrl = new URL(targetUrlStr); } catch (e) { return new Response("无效的 URL 格式", { status: 400 }); } // 构造发往源站的请求,伪装 Origin 和 Referer 防盗链 const proxyRequest = new Request(targetUrl, request); proxyRequest.headers.set("Origin", targetUrl.origin); proxyRequest.headers.set("Referer", targetUrl.origin); // 移除原始请求中的 Host 头,避免回源出错 proxyRequest.headers.delete("Host"); const response = await fetch(proxyRequest); // 判断响应内容是否为 m3u/m3u8 播放列表 const contentType = response.headers.get("content-type") || ""; const isPlaylist = contentType.toLowerCase().includes("mpegurl") || targetUrlStr.split('?')[0].endsWith(".m3u") || targetUrlStr.split('?')[0].endsWith(".m3u8"); if (isPlaylist) { // 如果是播放列表,需要重写其中的链接 let text = await response.text(); const workerUrl = url.origin + url.pathname; // 按行解析并替换 URL const lines = text.split('\n'); const rewrittenLines = lines.map(line => { line = line.trim(); // 1. 处理以非 # 开头的行(通常是实际的视频流链接) if (line && !line.startsWith('#')) { let fullUrl; try { // 将可能的相对路径转换为绝对路径 fullUrl = new URL(line, targetUrlStr).toString(); } catch(e) { fullUrl = line; } // 重写为 Worker 代理链接 return `${workerUrl}?url=${encodeURIComponent(fullUrl)}`; } // 2. 处理标签中包含的 URI(例如 #EXT-X-KEY 中的解密密钥或某些嵌套列表) if (line.startsWith('#EXT-X-')) { return line.replace(/URI="([^"]+)"/g, (match, p1) => { let fullUrl; try { fullUrl = new URL(p1, targetUrlStr).toString(); } catch(e) { fullUrl = p1; } return `URI="${workerUrl}?url=${encodeURIComponent(fullUrl)}"`; }); } // 其他标签行保持不变 return line; }); return new Response(rewrittenLines.join('\n'), { status: response.status, headers: { "Access-Control-Allow-Origin": "*", "Content-Type": "application/vnd.apple.mpegurl", "Cache-Control": "no-cache" } }); } // 如果不是播放列表(例如 .ts 视频切片),则直接将数据流转发给客户端 const responseHeaders = new Headers(response.headers); responseHeaders.set("Access-Control-Allow-Origin", "*"); return new Response(response.body, { status: response.status, headers: responseHeaders }); } };