Serving Multiple B2 Buckets with One Custom Subdomain Using Cloudflare

Hey everyone!

If you’re using Backblaze B2 for storage and want to enhance the appearance of your URLs with a custom subdomain, you can easily set it up to serve multiple B2 buckets. Here’s a step-by-step guide on how to achieve this using Cloudflare.

Disclaimer: This guide is based on my experience and research. There might be alternative or better methods, so feel free to suggest improvements or corrections.

Materials Needed:

  • Custom Subdomain: For example, b2.rojosalas.com (Replace with your own).
  • CNAME for Backblaze: f002.backblazeb2.com (Based on your B2 Friendly URL).

Step 1: Set Up Your CNAME Record

  1. Log in to Cloudflare:

    • Access the Cloudflare Dashboard and select your domain.
  2. Navigate to DNS Settings:

    • Click on the DNS tab.
  3. Add a CNAME Record:

    • This CNAME record will direct requests from your custom subdomain to your Backblaze B2 bucket endpoint.

    • Type: CNAME

    • Name: b2

    • Target: f002.backblazeb2.com

    • Proxy Status: Proxied (This allows Cloudflare to handle requests and apply your rules).

Step 2: Create a Cloudflare Transform Rule

  1. Navigate to Transform Rules:

    • Go to Rules > Transform Rules in the Cloudflare dashboard.
  2. Create a New Transform Rule:

    • Click on Create Transform Rule.
  3. Configure the Rule:

    • This rule will ensure that requests to your custom subdomain are properly mapped to the Backblaze B2 URL with the /file prefix.

    • Name: Provide a name for your rule (e.g., “Rewrite Backblaze B2 Paths”).

    • When incoming requests match:

      • Expression: (http.host eq "b2.rojosalas.com") or (http.host eq "https://b2.rojosalas.com")
      • Path Matching: No separate field; include it directly in the rule.
    • Rewrite URL:

      • Rewrite to: Dynamic
      • Value: concat("/file", http.request.uri.path)

Example Usage

With the transform rule in place, you can now use your subdomain to access multiple buckets through different subdirectories. Here’s how it works:

  • BucketA:

    • URL: https://b2.rojosalas.com/bucketA/images/pic1.png
    • Mapped to: https://f002.backblazeb2.com/file/bucketA/images/pic1.png
  • BucketB:

    • URL: https://b2.rojosalas.com/bucketB/images/pic2.png
    • Mapped to: https://f002.backblazeb2.com/file/bucketB/images/pic2.png

This setup allows you to conveniently reference and serve files from multiple Backblaze B2 buckets under a single custom subdomain.

Note: This guide is based on my working knowledge and research. There could be alternative or more efficient ways to achieve this, so if you spot any errors or have suggestions, please share them so I can update the post.