C# / .NETSecurityDevOps
Misc
Cloudflare Worker Conditional Reverse Proxy
Alexandru Puiu
Alexandru Puiu
January 12, 2020
1 min

Cloudflare worker to load content from subdomain/alternate location and replace references to subdomain/alternate location.

addEventListener('fetch', event => {
  var url = new URL(event.request.url);
  if (url.pathname.startsWith('/blog') || url.pathname === '/blog') {
    event.respondWith(handleBlog(event, url));
  } else {
    event.respondWith(fetch(event.request));
  }
})

async function handleBlog(event, url) {
  // Load subdomain content / reverse proxy mysite.com/blog to blog.mysite.com subdomain
  var originUrl = url.toString().replace('https://mysite.com/blog', 'https://blog.mysite.com');
  
  // Load content
  let response = await fetch(originUrl);

  // Make sure we only modify text, not images
  let type = response.headers.get("Content-Type") || "";
  if (!type.startsWith("text/")) {
    return response;
  }

  // Read response body
  let text = await response.text();

  // Modify it
  let modified = text.replace(/blog.mysite.com/g, "mysite.com/blog")

  // Return modified response
  return new Response(modified, {
    status: response.status,
    statusText: response.statusText,
    headers: response.headers
  });
}


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

Clouflare Worker Reverse Proxy
Reverse Proxy Cloudflare Worker
June 03, 2021
1 min
Enumeration Attacks
C# / .NET
Protect Against Enumeration Attacks in 2022
July 15, 2022
1 min
Signing Commits
DevOps
Signing Git Commits Using YubiKey on Windows
February 11, 2020
5 min
© 2022, All Rights Reserved.

Quick Links

Get In TouchAbout Me

Social Media