Skip to content

Commit

Permalink
Enable serving of index.html pages for requests ending in /
Browse files Browse the repository at this point in the history
This then allow static web sites to be served properly from an R2
bucket.
  • Loading branch information
ncw committed Aug 4, 2022
1 parent dbb1e64 commit 882de2f
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ interface Env {
ALLOWED_ORIGINS?: string,
CACHE_CONTROL?: string,
PATH_PREFIX?: string
INDEX_FILE?: string
}

type ParsedRange = { offset: number, length: number } | { suffix: number };
Expand Down Expand Up @@ -36,7 +37,7 @@ export default {
}

const url = new URL(request.url);
if (url.pathname === "/") {
if (!env.INDEX_FILE && url.pathname === "/") {
return new Response("OK");
}

Expand All @@ -48,7 +49,12 @@ export default {

if (!response || !response.ok) {
console.warn("Cache miss");
const path = (env.PATH_PREFIX || "") + decodeURIComponent(url.pathname.substring(1));
var path = (env.PATH_PREFIX || "") + decodeURIComponent(url.pathname.substring(1));

// Look for index file if asked for a directory
if (env.INDEX_FILE && (path.endsWith("/") || path === "")) {
path += env.INDEX_FILE;
}

let file: R2Object | R2ObjectBody | null | undefined;

Expand Down
4 changes: 4 additions & 0 deletions wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ CACHE_CONTROL = "max-age=86400"
# The string to prepend to each file path. Optional, nothing is prepended to the path if unset.
PATH_PREFIX = ""

# Index file to search for on directory requests, set to "" to disable indexes
#INDEX_FILE = ""
INDEX_FILE = "index.html"

[[r2_buckets]]
binding = "R2_BUCKET"
bucket_name = "kot" # Set this to your R2 bucket name. Required
Expand Down

0 comments on commit 882de2f

Please sign in to comment.