chandywerks.dev

Static Website on Backblaze with a Cloudflare Worker

Cloud

CloudFlare DNS custom worker domain

Backblaze offers 10 GB of storage for free and CloudFlare offers free data transfer from backblaze, combining these services you can host a fast and reliable static website with SSL for little to no cost.

To get started you'll need a public B2 storage bucket in Backblaze and a DNS zone in Cloudflare.

Cloudflare Worker

This worker script proxies requests to the B2 origin and caches the response on Cloudflare.

Add this script under Workers & Pages

export default {
async fetch(req, env, ctx) {
// Cached response
let res = await caches.default.match(req);
if (res) return res;

// Fetch object from origin
let reqPath = new URL(req.url).pathname;
reqPath = reqPath.replace(/\/$/, ''); // Remove trailing slash
if (!reqPath.includes('.')) // Check file extension
reqPath += '/index.html'; // Default to index page

res = await fetch(env.ORIGIN + reqPath);
if (res.status === 404) // Object not found
res = await fetch(env.ORIGIN + '/404.html');

// Configure content cache
res = new Response(res.body, res);
const ttl = res.headers.get('content-type').startsWith('text')
? 14400 : 31536000; // Cache text 4 hours, 1 year default
res.headers.set('cache-control', 'public, max-age=' + ttl);

// Cache and return response
ctx.waitUntil(caches.default.put(req, res.clone()));
return res;
},
};

Configure these worker settings

Cloudflare worker settings for Domains & Routes and Variables and Secrets

  1. Route all requests through the worker
  2. Custom domain creates a DNS record
  3. ORIGIN is the public bucket URL
    https://f002.backblazeb2.com/file/<BUCKET_NAME>