본문 바로가기

카테고리 없음

Cloudflare CDN 설정하기(비디오 캐싱)

cdn을 키기 위해 workers를 이용하자 

 

worker.js 

export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);
    const videoPath = url.pathname.slice(1);

    const cacheKey = new Request(url.toString(), request);
    const cache = caches.default;

    // 캐시에서 먼저 확인
    let response = await cache.match(cacheKey);
    if (response) {
      return response;
    }

    // R2에서 직접 가져오기
    const object = await env.MY_BUCKET.get(videoPath);
    if (!object) {
      return new Response('Video not found', { status: 404 });
    }

    response = new Response(object.body, {
      headers: {
        'Content-Type': 'video/mp4',
        'Cache-Control': 'public, max-age=86400',
        'ETag': object.httpEtag, // object.etag 대신
        'Accept-Ranges': 'bytes'
      }
    });

    // ⬅️ 캐시 저장 예약 (Worker 응답 이후에도 백그라운드에서 저장)
    ctx.waitUntil(cache.put(cacheKey, response.clone()));

    return response;
  }
};

 

 

 

 

 

 

 

아래는 cdn이 된 상태이다.