【问题标题】:Cloudflare worker to redirect to new URL doesn’t workCloudflare 工作人员重定向到新 URL 不起作用
【发布时间】:2020-03-27 13:23:42
【问题描述】:

我正在尝试根据this post 在我的网站上设置一个博客(作为子目录/子页面)。因此,我的网站托管在 here 上,我希望 this subpage (/officiano) 呈现来自我的其他网站之一 - this custom domain 甚至它的 Netlify 域的内容。

我已经使用路由 .remotework2020.com/ 设置了一个可能的工作人员,并且工作人员的代码与帖子中的代码相同。我可以看到评估正确发生(通过控制台日志),但是,当我转到子目录时,它只会引发 404 错误。

谁能帮助解决这个问题?

编辑:

将整个工作代码粘贴到下面:

// 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))
})

【问题讨论】:

    标签: cloudflare cloudflare-workers


    【解决方案1】:

    您似乎已在路线*.remotework2020.com/* 上配置了您的工作人员。但是,这与remotework2020.com/officiano 不匹配,因为模式的前导*. 部分不匹配。例如,该模式将匹配 www.remotework2020.com/officiano,但您的主机名中没有 www.

    尝试将路由更改为remotework2020.com/*

    【讨论】:

    • 谢谢肯顿!尝试更改路线,但仍然抛出 404 :(
    • @Hrishikesh_Pardeshi 看起来代码正在运行,但目标站点 (theremoteweekly.com) 本身返回 404。
    猜你喜欢
    • 2021-02-16
    • 1970-01-01
    • 2021-08-25
    • 2016-05-24
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    • 2020-04-03
    相关资源
    最近更新 更多