Skip to content

Control cache access with WAF and Snippets

When you make an R2 bucket publicly accessible for caching (via a Custom Domain), anyone who knows the URL can access the content. To restrict access, you can use Cloudflare's WAF to validate requests before they reach the cache or your bucket.

The following diagram illustrates the flow of a request through WAF, Cache, and R2. WAF custom rules run before cache rules in the request pipeline, so invalid requests are blocked before consuming cache resources.

flowchart LR
accTitle: Connections with Cloudflare
A[User's request] --> B[WAF] --> C[Cache] --> D[R2]

Presigned URLs

A presigned URL is a regular URL with a cryptographic token appended to it. The token contains a hash-based message authentication code (HMAC) computed from the URL path, a timestamp, and a secret key shared between the signing service and the validator. Anyone with the URL can access the content until the token expires, but the token cannot be reused for a different URL path.

You can presign URLs similar to S3, enabling you to share direct access to your content with an associated timeout. This approach can be implemented using a combination of Snippets, Rules, or Cloudflare Workers.

For optimal performance, we recommend separating the creation and validation processes:

  • Snippets for HMAC creation (signing the URL)
  • WAF custom rules for HMAC validation (verifying the token on each request)

In the Workers documentation, the Signing requests example shows how to both generate and verify signed requests using HMAC. The Workers implementation is compatible with the WAF's is_timed_hmac_valid_v0() validation function, so you can sign with Workers and validate with WAF custom rules, or handle both in Workers.