Redirect Backblaze B2 not_found with Cloudflare Worker

Utilizing Cloudflare Workers to redirect Backblaze B2 404s

Redirect Backblaze B2 not_found with Cloudflare Worker
Backblaze B2 missing file

Backblaze combined with Cloudflare seems to make the most sense if you're selfhosting, that's because Cloudflare is Backblaze's Bandwidth Alliance partner. What that means is that we can take advantage of Cloudflare's performance and free data transfer between Backblaze B2 and Cloudflare. Mainly because of $0 Egress fees.

Now you'll notice when accessing the B2 path that no longer available or invalid you'd see this:

{
  "code": "not_found",
  "message": "File with such name does not exist.",
  "status": 404
}

Doesn't look very nice does it? Now insert Cloudflare Worker to the picture. Using the worker, we can automatically redirect the User when they encounter the Error 404.

On the Free plan, you'll get up to 100,000 requests a day.

Prerequites:

  • Cloudflare account is setup
  • Domain is added to Cloudflare (optional)
  • Buy me a 🧋 on Ko-fi

Creating a Worker in Cloudflare

  1. Logon to Cloudflare
  2. You'll be redirected to your Dashboard, on the left column, select Workers
    Screenshot-2023-02-22-124608
  3. Run through the basic setup requirements
  4. Create a Service and select HTTP router
  5. Give the Service a friendly name, then click Create service
  6. Now you'll be in the overview of the Service, click on Quick edit on the top right
  7. Paste the following code and modify the bucketUrl and the Response.redirect URLs accordingly
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  const url = new URL(request.url)
  const bucketUrl = 'https://media.mastodon.sg'

  // Redirect to the new URL if the requested path is the root path '/'
  if (url.pathname === '/') {
    return Response.redirect('https://mastodon.sg/', 302)
  }

  const b2Url = bucketUrl + url.pathname

  try {
    const response = await fetch(b2Url)
    if (response.status !== 404) {
      return response
    }
  } catch (e) {
    // If there was an error fetching the file, return a 404 response
    return new Response('File not found', { status: 404 })
  }

  // Otherwise, redirect the user to a different URL
  return Response.redirect('https://mastodon.sg/404', 302)
}
  1. Click Save and Deploy below
  2. Now to assign subdomain to your worker, you'll need to Add route
  3. Go to the Trigger tab and click on Add route
  4. Type in the subdomain and the zone
    Screenshot-2023-02-22-125235
  5. Save and that's it!

Now when they get to an invalid path, they'll be redirected.