Skip to content
Cloudflare Docs

Point to R2 bucket with a custom domain

Last reviewed: 13 days ago

This example configures an origin rule and a DNS record to point to an R2 bucket configured with a custom domain.

The procedure will use the following example values:

URL that website visitors will accessmycustomerexample.com/images/*
R2 bucket custom domainimagesbucket.example.com

When configuring your R2 bucket's custom domain, use a custom domain that you do not plan to use in production (imagesbucket.example.com in this example).

1. Configure custom domain in your Pages project

  1. Log in to the Cloudflare dashboard and select your account.
  2. Go to R2 Object Storage and select your bucket.
  3. On the bucket page, select Settings.
  4. Under Public access > Custom Domains, select Connect Domain.
  5. Enter the domain name you want to connect to — imagesbucket.example.com in this example — and select Continue.
  6. Review the new record that will be added to the DNS table and select Connect Domain.

Your domain is now connected. The status takes a few minutes to change from Initializing to Active, and you may need to refresh to review the status update. If the status has not changed, select the ... next to your bucket and select Retry connection.

To view the added DNS record, select ... next to the connected domain and select Manage DNS.

2. Create origin rule to rewrite host header and override DNS record

In your mycustomerexample.com zone, create an origin rule with the following configuration:

If incoming requests match

FieldOperatorValue
URI Pathwildcard/images/*

If using the Expression Editor, enter the following expression:

(http.request.uri.path wildcard "/images/*")

Set origin parameters

  • Value after Host header > Rewrite to: imagesbucket.example.com
  • Value after DNS record > Override to: imagesbucket.example.com

3. (Optional) Configure URL rewrite

In our example, the URL that website visitors will access starts with /images. However, images stored in the example R2 bucket do not have this initial URL segment.

Use a URL rewrite to remove the /images segment from the URL path. Cloudflare provides a rule template in the dashboard called Rewrite Path for Object Storage Bucket that you can use to configure the required rewrite.

  1. Go to Rules > Overview.

  2. Select Create rule > URL Rewrite Rule.

  3. Enter a descriptive name for the rule in Rule name.

  4. In If incoming requests match, select Wildcard pattern.

  5. Enter the following value in Request URL:

    https://<YOUR_HOSTNAME>/images/*

    In the current example, the value would be https://mycustomerexample.com/images/*.

  6. In Then rewrite the path and/or query, enter the following values under Path:

    Target pathRewrite to
    [/] images/*[/] ${1}
  7. Select Deploy.

More resources