For Workers & Pages, what is the name of the domain?
What is the issue or error you’re encountering
I’m trying to expose a R2 bucket publicly using a Worker as a router. Whenever I do wrangler dev --remote the request.url is the production workers.dev URL instead of localhost.
What are the steps to reproduce the issue?
Create a worker with this index.ts:
interface Env {
MY_BUCKET: R2Bucket
}
function objectNotFound(objectName: string): Response {
return new Response(`<html><body>R2 object "<b>${objectName}</b>" not found</body></html>`, {
status: 404,
headers: {
'content-type': 'text/html; charset=UTF-8'
}
})
}
export default {
async fetch(request, env): Promise<Response> {
const url = new URL(request.url)
const pathname = url.pathname;
let objectName = url.pathname.slice(1)
console.log(request.url);
// 1. Redirect /something/index.html → /something
// FIXME: when I run npx wrangler dev --remote, and go to
// localhost:8787/dexterleng/index.html
// request.url is https://<worker name>.hello-bbc.workers.dev/dexterleng/index.html
console.log(url.origin);
if (pathname.endsWith('/index.html')) {
const newUrl = url.origin + pathname.slice(0, -'/index.html'.length)
return Response.redirect(newUrl, 301)
}
// 2. Redirect /something → /something/
// (but don't do it if it's just `/`)
if (pathname !== '/' && !pathname.endsWith('/')) {
const newUrl = url.origin + pathname + '/'
return Response.redirect(newUrl, 301)
}
// 3. When accessing /something/, serve /something/index.html
if (pathname.endsWith('/')) {
objectName += 'index.html'
}
console.log(`${request.method} object ${objectName}: ${request.url}`)
if (request.method === 'GET') {
const object = await env.MY_BUCKET.get(objectName, {
range: request.headers,
onlyIf: request.headers,
})
if (object === null) {
return objectNotFound(objectName)
}
const headers = new Headers()
object.writeHttpMetadata(headers)
headers.set('etag', object.httpEtag)
if (object.range) {
headers.set("content-range", `bytes ${object.range.offset}-${object.range.end ?? object.size - 1}/${object.size}`)
}
const status = object.body ? (request.headers.get("range") !== null ? 206 : 200) : 304
return new Response(object.body, {
headers,
status
})
}
return new Response(`Unsupported method`, {
status: 400
})
}
} satisfies ExportedHandler<Env>;
go to a path that will be rewritten e.g. /something/index.html
instead of redirecting to localhost:/something/, you will get redirected to workers.dev/something/