Hrishikesh_Pardeshi
Hrishikesh_Pardeshi

Reputation: 995

Cloudflare worker to redirect to new URL doesn’t work

I am trying to set up a blog on my website (as a subdirectory/ subpage) per this post. So, my website is hosted here and I want this subpage (/officiano) to render content from one of my other websites - this custom domain or even its Netlify domain.

I have set up a Couldflare worker with the route .remotework2020.com/ and the code for the worker is identical to the one in the post. I can see the evaluations happening correctly (through console log), however, it just throws up 404 error when I go to the subdirectory.

Could anyone possibly help on how to debug the issue?

EDIT:

Pasting the entire worker code below:

// keep track of all our blog endpoints here
const myBlog = {
  hostname: "theremoteweekly.com",
  targetSubdirectory: "/officiano",
  assetsPathnames: ["/public/", "/assets/"]
}

async function handleRequest(request) {
  // returns an empty string or a path if one exists
  const formatPath = (url) => {
    const pruned = url.pathname.split("/").filter(part => part)
    return pruned && pruned.length > 1 ? `${pruned.join("/")}` : ""
  }

  const parsedUrl = new URL(request.url)
  const requestMatches = match => new RegExp(match).test(parsedUrl.pathname)

  // if its blog html, get it
  if (requestMatches(myBlog.targetSubdirectory)) {
    console.log("this is a request for a blog document", parsedUrl.pathname)
    const targetPath = formatPath(parsedUrl)
    console.log(targetPath)
    console.log(`https://${myBlog.hostname}/${targetPath}`)
    return fetch(`https://${myBlog.hostname}/${targetPath}`)
  }

  // if its blog assets, get them
  if ([myBlog.assetsPathnames].some(requestMatches)) {
    console.log("this is a request for blog assets", parsedUrl.pathname)
    const assetUrl = request.url.replace(parsedUrl.hostname, myBlog.hostname);

    return fetch(assetUrl)
  }

  console.log("this is a request to my root domain", parsedUrl.host, parsedUrl.pathname);
  // if its not a request blog related stuff, do nothing
  return fetch(request)
}

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request))
})

Upvotes: 0

Views: 1387

Answers (1)

Kenton Varda
Kenton Varda

Reputation: 45336

It looks like you have configured your worker on the route *.remotework2020.com/*. However, this does not match remotework2020.com/officiano, because the leading *. part of the pattern is not matched. For example, the pattern would match www.remotework2020.com/officiano, but you don't have a www. in your hostname.

Try changing the route to remotework2020.com/*.

Upvotes: 1

Related Questions