Cloudflare Worker Conditional Reverse Proxy

< 1 min read 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
  });
}

Building a fast and secure blog – Part 3

9 min read

Setting up Cloudflare

Sign up for a free account at https://www.cloudflare.com/.

Upgrading to Pro has some definite benefits

Add your site

As soon as you log in, you have the option of adding your first site

Verify your DNS records

At the next step it will try to detect and import all your existing DNS records. You’ll next be changing your nameservers to use Cloudflare’s nameservers, so make sure all your DNS records are present. There is an option to avoid this if the situation really requires it, and proceed with CNAME records, but you’ll have to reach out to Cloudflare support to discuss those options.