Hosting on Cloudflare R2
Cloudflare R2 is an S3-compatible object storage service. It works well with Surreal CMS because publishing
a static website is just writing files, like index.html, about.html, images, and
stylesheets. This page walks you through setting up a bucket in the Cloudflare dashboard, connecting it to
Surreal CMS, and adding the rules that turn a bucket full of files into a real website.
R2 isn't Cloudflare Pages
Pages copies your files to Cloudflare's edge network when you deploy. R2 stores your files in one region and serves them over a custom domain. Cloudflare caches things like CSS, JavaScript, and images near your visitors, but it doesn't cache HTML by default. That means a visitor in Sydney requesting a page from a bucket in North America waits on that region for every HTML request. That's perfectly fine for most websites. Just know it's not the same as a globally cached deploy.
Before you start
All of the following need to be true before you begin:
- You have a Cloudflare account with R2 enabled. Turning R2 on requires a payment method, but the free tier still applies.
- Your website's domain is an Active zone on that same Cloudflare account. Custom domains and rules only work when Cloudflare is handling DNS for the domain.
- You're using one bucket per website. Connecting a custom domain makes the entire bucket readable at that hostname, so don't store drafts, backups, or anything private in it.
To add your domain to Cloudflare, use the apex, example.com, not www.example.com.
Then point your registrar's nameservers to the two Cloudflare nameservers shown on the domain's
Overview page. Wait until the status reads Active rather than
Pending before continuing.
Your domain has to be on Cloudflare
If your domain stays with your registrar's DNS and never becomes a Cloudflare zone, the custom domain and rules in this guide won't work. Move the domain to Cloudflare first, then come back.
How the pieces fit together
R2 has no "static website" mode, no index document setting, and no option to hide file extensions. Those behaviors come from rules you create on your domain, not from the bucket.
| R2 bucket | Stores the files Surreal CMS publishes |
|---|---|
| Custom domain | Serves those files over HTTPS, e.g. https://www.example.com/index.html |
| URL rewrite rule | Makes / load index.html (required) |
| Second rewrite rule | Makes /about load about.html (optional) |
| Custom error rule | Shows your 404.html when a file is missing (optional, paid plans) |
Without the first rewrite rule, your homepage lives at
https://www.example.com/index.html instead of https://www.example.com/.
1. Create the bucket
Log in at dash.cloudflare.com. Use the sidebar on the account home page, the one with R2, Workers, and Domains. Don't use the sidebar you see after selecting a specific website.
- Go to Storage & Databases › R2 › Overview.
- If R2 isn't enabled yet, complete the checkout. You won't be billed until you exceed the free tier.
- Select Create bucket.
- Name it using lowercase letters, numbers, and hyphens, e.g.
my-website. - Choose a location. Automatic places the bucket near wherever you happen to be, or you can pick a hint closer to most of your visitors: Western/Eastern North America, Western/Eastern Europe, Asia-Pacific, or Oceania.
- Leave the storage class set to Standard and select Create bucket.
Location is permanent
Your files live in the region you choose. You can't move a bucket later. You'd have to create a new one and copy everything over. Pick the region closest to most of your visitors.
You can upload your website's files now using the Upload button, or you can leave the
bucket empty and let Surreal CMS publish them for you after you've connected everything. If you plan to
use a custom 404 page, add 404.html to the bucket at some point. To upload from the command
line, or to have an agent do it, see
Hosting an Agent-Built Website on Cloudflare R2.
Uploading by hand?
If you upload files through the Cloudflare dashboard, select an HTML file afterwards and confirm its
Content-Type is text/html. If it says application/octet-stream,
browsers will download the file instead of displaying it. Surreal CMS sets the correct content type
automatically when it publishes.
2. Create API credentials
Surreal CMS needs an API token to read and write files in your bucket.
- From Storage & Databases › R2 › Overview, open API Tokens. (Depending on your account, this may appear as a Manage link next to API Tokens.)
- Create an account or user API token.
- Set the permission to Object Read & Write.
- Scope the token to the bucket you just created, not to all buckets.
- Create the token, then copy the Access Key ID and Secret Access Key. The secret is only shown once.
You'll also need your Account ID, which is shown on the R2 Overview page. It's a 32-character string of letters and numbers.
3. Connect a custom domain
Your bucket needs a public hostname before it can serve a website. Pick a hostname on the zone you already
added, such as www.example.com, example.com, or something like
files.example.com.
- Open your bucket and go to Settings.
- Under Custom Domains, select Add (labeled Connect Domain on some accounts).
-
Enter the hostname by itself, e.g.
www.example.com. Don't includehttps://. - Select Continue, review the DNS record Cloudflare will create for you, then select Connect Domain.
- Wait until the status reads Active instead of Initializing. If it gets stuck, use the … menu and select Retry connection.
Once the domain is active, upload an index.html file if you haven't already and visit
https://www.example.com/index.html to confirm it loads. If you get a 404, the file's name
doesn't match the path you requested. Note that object names don't include the bucket name. If you
see an SSL error, the domain is probably still initializing.
Don't use the r2.dev URL
R2 offers a public development URL ending in r2.dev. Don't use it for a live website.
It's rate limited, it isn't meant for production, and the rules below won't run on it.
4. Connect your website to Surreal CMS
Log in to Surreal CMS, then select New Site on the Sites page. Choose Cloudflare R2 for the protocol and fill out the form.
| Name | The name you want to use for your website. (Only used in the CMS.) |
|---|---|
| URL |
The custom domain you connected above, e.g. https://www.example.com/Important! Use your custom domain here, not the r2.cloudflarestorage.com endpoint. That endpoint is the API we connect to, not your
website.
|
| Protocol | Cloudflare R2 |
| Account ID | Your Cloudflare account ID, found on the R2 overview page of your Cloudflare dashboard. |
| Bucket | The exact name of the bucket you created. |
| Access Key | The Access Key ID from your R2 API token. |
| Secret Access Key | The Secret Access Key from your R2 API token. |
| Home Folder | The folder that contains your homepage. Use the Browse button to navigate to it. For a bucket that holds a single website, this is usually the root of the bucket. |
| Upload Folder |
The folder that uploaded files will be stored in. Users can upload, rename, move, and delete anything
inside this folder, but nothing outside of it, so don't select one that contains webpages or
other important files. Create a folder called uploads for this purpose. See
best practices for why.
|
Select Test Connection to make sure everything works. If all goes well, you'll see Connection successful!
If the connection fails, double check your account ID and bucket name, and make sure your API token has Object Read & Write permission for this bucket.
5. Make your homepage load at /
Right now https://www.example.com/index.html works but
https://www.example.com/ doesn't. This rule fixes that. Unlike everything above, rules are
configured on your website in Cloudflare, not on the R2 bucket.
-
In the Cloudflare dashboard, switch from the account view into your domain, e.g.
example.com. - Go to Rules › Overview and select Create rule › URL Rewrite Rule. Ignore the templates at the top of the page, including the one for object storage buckets. Those strip a prefix from the path and won't do what you need.
- Name the rule
R2 directory index. - Under If incoming requests match…, choose Custom filter expression (not Wildcard pattern).
-
Add two conditions joined with And: Hostname equals your
hostname, and URI Path ends with
/. - Under Then…, set Path to Rewrite to… › Dynamic and enter this expression:
concat(http.request.uri.path, "index.html")
Set Query to Preserve, then select Deploy, not Save as Draft.
Now https://www.example.com/ serves index.html, and
https://www.example.com/blog/ serves blog/index.html. If
/index.html works but / still doesn't, the rule is probably still a draft,
was created on the wrong domain, or has a hostname that doesn't match.
Optional: Clean URLs
Most R2 websites keep .html in their URLs. Add this rule only if you want
https://www.example.com/about to serve about.html. The file in your bucket is
still named about.html. The rule only changes what R2 looks up, so the address bar stays clean.
Create another URL Rewrite Rule, name it R2 hide html extension, choose
Custom filter expression, and use the expression editor to enter the following. Replace the
hostname with your own.
(http.host eq "www.example.com" and not ends_with(http.request.uri.path, "/") and http.request.uri.path.extension eq "")
Set Path to Rewrite to… › Dynamic with this expression, set Query to Preserve, and deploy.
concat(http.request.uri.path, ".html")
This matches paths like /about and /blog/hello, and leaves
/styles.css and /images/logo.png alone because those already have an extension.
Two things to watch for: if a page is saved as about/index.html rather than
about.html, use /about/ instead, which the first rule already handles. And paths
that look like they have an extension, such as /v1.2/notes, won't match this rule.
Optional: A custom 404 page
A rewrite rule can't do this, because rewrites run before R2 answers and never learn that a file was missing. Instead, use a Custom Error Rule, which is available on Pro plans and above. On the Free plan, missing files show R2's generic error page.
-
Publish
404.htmlto your bucket and confirm it loads athttps://www.example.com/404.html. - On your domain, go to Rules › Overview and select Create rule › Custom Error Rule.
- Name the rule
R2 404 pageand choose Custom filter expression. - Enter the expression below, replacing the hostname with your own.
(http.host eq "www.example.com" and http.response.code eq 404)
-
Choose Deliver a custom error response ›
Custom error asset › Create new asset and enter
https://www.example.com/404.htmlas the URL. - Set the response code to 404 so search engines still see a not-found response.
- Select Deploy.
Editing your 404 page later
Cloudflare fetches your error page once and stores a copy. After you edit 404.html in Surreal
CMS, go back to the rule and fetch the custom error asset again, otherwise visitors will keep seeing the
old version.
Keeping published files fresh
Surreal CMS uploads every file with a Cache-Control: no-cache header, so edits show up as soon
as you publish. Some Cloudflare settings override that header, which leaves visitors and the Surreal CMS
editor seeing old stylesheets for hours. On your domain in Cloudflare, make sure:
- Caching › Configuration › Browser Cache TTL is set to Respect Existing Headers.
- No Cache Rule or Page Rule for your hostname uses Cache Everything or overrides the Edge TTL.
After changing these, select Purge Everything once to clear old copies.
Fonts and scripts in the editor
Surreal CMS loads your page from its own origin to edit it, so web fonts and JavaScript modules are
cross-origin requests in the editor, and browsers block them unless the response allows it. Without that
permission, the editor shows your site in a fallback font and type="module" scripts
don't run. Visitors aren't affected.
R2 adds the permission from a CORS policy on the bucket. Open the bucket's Settings, select Add CORS policy under CORS Policy, and enter this on the JSON tab:
[
{
"AllowedOrigins": ["*"],
"AllowedMethods": ["GET"]
}
]
The custom domain only includes the header when a request has an Origin header, which browsers
send for these requests. If the domain was already serving traffic, purge its cache once so cached files
pick up the header.
Testing your setup
Once everything's in place, check these URLs. Replace the hostname with your own.
/index.html |
Your homepage. This works even without any rules. |
|---|---|
/ |
Your homepage, once the directory index rule is deployed. |
/about.html |
Your about page. |
/about |
Your about page, but only if you added the clean URL rule. |
/styles.css |
Stylesheets, images, and other static files. |
/this-does-not-exist |
R2's error page, or your 404.html if you added a custom error rule. |
Performance and cost
Your bucket has one home region, so your website isn't stored in every Cloudflare data center. Serving it through a custom domain routes visitors through Cloudflare first, which caches CSS, JavaScript, images, fonts, and other static files near your visitors. HTML isn't cached by default.
In practice, a visitor in Australia loading /styles.css gets a copy from a nearby Cloudflare
data center after the first request, though Cloudflare still checks the bucket for changes each time because
of the no-cache header. Loading / or /about means waiting on your
bucket's region. If most of your audience is far from the bucket, HTML will feel slower than it would
on a service that caches pages at the edge. You can add cache rules for HTML later, but then you'll
need to purge those URLs whenever Surreal CMS publishes, or visitors will see stale pages.
R2 charges for storage and operations, but not for bandwidth. Storage is $0.015 per GB per month, writes are $4.50 per million, and reads are $0.36 per million. The monthly free tier covers 10 GB of storage, 1 million writes, and 10 million reads. A typical brochure website stays comfortably within it, and image-heavy websites tend to be inexpensive because there's no egress charge.
A few other limits worth knowing: the custom domain exposes your entire bucket, there's no atomic deploy or preview URL since publishing overwrites files in place, and your domain has to stay on Cloudflare for the custom domain and rules to keep working.
Should you use R2?
R2 is a good fit if you want an S3-style workflow. Connect a bucket, publish files, serve them on your domain. Combined with the directory index rule, it gives you a straightforward static website with free bandwidth.
If you need your HTML to be fast everywhere, with /, clean URLs, and custom 404 pages built in,
Cloudflare Pages is the better choice. It copies your files to Cloudflare's network at deploy time
instead of tying them to a single region. It also uses a different publishing method than the S3 API Surreal
CMS uses for R2, so we'll cover that setup separately.
Checklist
- Your domain is an Active zone on the same Cloudflare account as R2
- One bucket per website, Standard storage class, with the location chosen deliberately
- An API token scoped to that bucket with Object Read & Write permission
- A custom domain connected, with
/index.htmlloading in a browser - A rewrite rule appending
index.htmlto paths ending in/ - Optionally, a rewrite rule appending
.htmlto extensionless paths - Optionally, a custom error rule for
404.htmlon a paid plan - A CORS policy on the bucket allowing
GETfrom any origin - Browser Cache TTL set to Respect Existing Headers, with no cache rules overriding the Edge TTL
- No private files in the bucket
If you run into trouble getting connected, feel free to contact us for help!