首页 > 解决方案 > 使用 Cloudflare 的 S3 托管网站为任何路由返回 404 状态代码

问题描述

我有一个在 Cloudflare 后面运行良好的 S3 托管网站,其内容如下:

ss1

example.com/工作正常

example.com/test也可以,但是网络选项卡中的文档本身自然会返回 404,因为 /test 在 S3 上不存在。

这是 SEO 的问题,如何配置 Cloudflare 将 404 视为 200?

在 Cloudfront 中,我通常这样做:

SS2

但是我在 Cloudflare 中找不到对应的配置。这是否必须在 Cloudflare 工作人员中完成?在工人存在之前人们做了什么?

标签: amazon-s3cloudflare

解决方案


事实证明,人们只是没有在工人之前使用 Cloudflare 在 S3 上托管,如果他们这样做了,他们并不关心/注意到他们的路线会返回 404。

无论如何,这是 Cloudflare 工作人员强制返回代码 200 的解决方案:

addEventListener('fetch', event => {
  event.respondWith(fetchAndApply(event.request))
})

async function fetchAndApply(request) {
  let originalResponse = await fetch(request)

  const contentType = originalResponse.headers.get("Content-Type")

  // Only bother with index pages (not assets)
  if (contentType && contentType.includes("text/html")) {

    // Force 404's from S3 to return as 200 to prevent Google indexing issues
    let response = new Response(originalResponse.body, {
        ...originalResponse,
        status: 200, 
        statusText: 'OK'
      }
    )

    // Don't cache index.html
    response.headers.set('Cache-Control', 'max-age=0')

    return response
  }

  return originalResponse
}

推荐阅读