Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

301 Redirect for specific page with CloudFront

I'm rebuilding my website. The new one will be hosted on S3 with CloudFront in front of it.

How do I create a few redirects for some URLs which existed on the old site, but won't on the new site?

example.com/thing?id=blah for example I'll be wanting to redirect to othersite.com/other-path

like image 738
Costa Michailidis Avatar asked Dec 19 '22 07:12

Costa Michailidis


1 Answers

You can't do redirects in CloudFront, but since your origin is S3, you can do redirects in that.

First, you'll need to make sure your CloudFront origin for s3 is configured correctly. You can not do website redirects with the standard REST API (which is the auto-complete option).

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.

(Source: Using Amazon S3 Origins and Custom Origins for Web Distributions)

Next, if your redirect-from links do indeed have query parameters in them which you need to evaluate based on, you'll need to 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 it should be possible.

Forward all, cache based on all

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

(Source: Query String Forwarding and Caching)

Finally, set up your S3 bucket with Routing Rules for the desired redirects. Given your example, it would look something like this:

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

(Source: Syntax for Specifying Routing Rules)

The final point to bring to your attention would be the syntax of routing rules themselves. The Condition being placed on your routing rule is KeyPrefixEquals. There is no KeyEquals Condition available.

This means that if you for example had thing?id=blah and thing?id=blah2 Routing Rules, the order will matter. Put blah2 before blah, or you'll always match on blah.

There are many other routing rule options available, that will allow you to change protocol, redirect to another domain instead of just rewriting the path, etc. Check out the documentation on routing rules for more information.

like image 176
Luke Waite Avatar answered Dec 28 '22 11:12

Luke Waite