C# / .NETDevOpsMisc
Misc
Reverse Proxy Cloudflare Worker
Alexandru Puiu
Alexandru Puiu
June 03, 2021
1 min

Clouflare worker reverse proxy any content

addEventListener("fetch", (event) => {
  event.respondWith(
    handleRequest(event.request).catch(
      (err) => new Response(err.stack, { status: 500 })
    )
  );
});

async function handleRequest(request) {
  const { pathname, searchParams, host } = new URL(request.url);

  const url = new URL(request.url)
  url.hostname = "photos.example.com"

  const newRequest = new Request(
    url.toString(),
    request
  )

  let response = await fetch(newRequest,
  {
    cf: {
      // Always cache this fetch regardless of content type
      cacheTtlByStatus: { "200-299": 16070400, 404: 1, "500-599": 0 }
    },
  });

  response = new Response(response.body, response)

  // Set cache control headers to cache on browser for 25 minutes  
  response.headers.set("Cache-Control", "public, max-age=16070400")
  
  return response
}

Tags

securitycloudflare
Alexandru Puiu

Alexandru Puiu

Engineer / Security Architect

Systems Engineering advocate, Software Engineer, Security Architect / Researcher, SQL/NoSQL DBA, and Certified Scrum Master with a passion for Distributed Systems, AI and IoT..

Expertise

.NET
RavenDB
Kubernetes

Social Media

githubtwitterwebsite

Related Posts

Cloudflare Conditional Reverse Proxy
Cloudflare Worker Conditional Reverse Proxy
January 12, 2020
1 min
Authentication in HttpClientFactory
C# / .NET
Authentication in Http Client Factory
December 21, 2022
1 min

Subscribe To My Newsletter

I'll only send worthwhile content I think you'll want, less than once a month, and promise to never spam or sell your information!
© 2023, All Rights Reserved.

Quick Links

Get In TouchAbout Me

Social Media