使用 CloudFront 对特定页面进行 301 重定向

301 Redirect for specific page with CloudFront

我正在重建我的网站。新的将托管在 S3 上,前面是 CloudFront。

如何为旧站点上存在但新站点上没有的某些 URL 创建一些重定向?

example.com/thing?id=blah 例如我想重定向到 othersite.com/other-path

您无法在 CloudFront 中进行重定向,但由于您的来源是 S3,因此您可以在其中进行重定向。

首先,您需要确保 s3 的 CloudFront 源配置正确。您不能使用标准 REST API(自动完成选项)进行网站重定向。

Enter the Amazon S3 static website hosting endpoint for your bucket. This value appears in the Amazon S3 console, on the Properties page under Static Website Hosting.

When you specify the bucket name in this format, you can use Amazon S3 redirects and Amazon S3 custom error documents.

(来源:Using Amazon S3 Origins and Custom Origins for Web Distributions

接下来,如果您的重定向来源链接中确实包含您需要根据其进行评估的查询参数,则您需要 make sure CloudFront is configured to forward query parameters. I should note, I've never had to build redirects in s3 that key of query-string parameters, but according to this SO answer 它应该是可能的。

Forward all, cache based on all

Choose this option if your origin server returns different versions of your objects for all query string parameters.

(来源:Query String Forwarding and Caching

最后,set up your S3 bucket with Routing Rules 用于所需的重定向。根据您的示例,它看起来像这样:

<RoutingRules>
  <RoutingRule>
  <Condition>
    <KeyPrefixEquals>thing?id=blah</KeyPrefixEquals>
  </Condition>
  <Redirect>
    <ReplaceKeyWith>other-path</ReplaceKeyWith>
  </Redirect>
  </RoutingRule>
</RoutingRules>

(来源:Syntax for Specifying Routing Rules

最后一点要提请您注意路由规则本身的语法。放置在路由规则上的条件是 KeyPrefixEquals。没有 KeyEquals 可用的条件。

这意味着如果您有 thing?id=blahthing?id=blah2 路由规则,顺序将很重要。将 blah2 放在 blah 之前,否则您将始终匹配 blah.

还有许多其他可用的路由规则选项,允许您更改协议、重定向到另一个域而不是仅仅重写路径等。查看 documentation on routing rules 了解更多信息。