DEV Community

Cover image for URL redirects with AWS S3 and Cloudfront
Vishnu Prassad
Vishnu Prassad

Posted on

2

URL redirects with AWS S3 and Cloudfront

Hosting a static website with S3 is awesome! It is Faster, Cheaper, Zero maintenance.

In this article, we will see how to do URL redirects on a website hosted with AWS S3 and Cloudfront.

There was a scenario which I was faced once in my company, One of our websites had deleted some old content and replaced it with new content and URL. And when people who google search for that particular content they get the old URL which doest exists.

To fix this issue the approach we had was to do add a temporary redirect for that old URL to the new one until it gets updated at google search.

The Fix

AWS S3 Static hosting provides an option to add redirection rules to the website hosted in a particular bucket. https://docs.aws.amazon.com/AmazonS3/latest/dev/how-to-page-redirect.html

In this particular case, the URL's we are going to use will be these,

https://example.com/content/old-content

and we will be redirecting this to

https://example.com/content/new/content

To add the rules,

  1. Click on your bucket
  2. Go to properties and click on static website hosting
  3. Under the redirection rules filed, put the following code

Redirect Rule,

<RoutingRules>
  <RoutingRule>
    <Condition>
      <KeyPrefixEquals>content/old-content/</KeyPrefixEquals>
    </Condition>
    <Redirect>
      <HostName>example.com</HostName>
<ReplaceKeyPrefixWith>content/new/content</ReplaceKeyPrefixWith>
    </Redirect>
  </RoutingRule>
</RoutingRules>

Please note, The HostName(Line 7*)* part is important if your S3 website is configured with Cloudfront. Else during redirect, the domain name will be replaced with the S3 website endpoint.

That's it. Now any requests coming to the old URL will be automatically redirected to the new one

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (1)

Collapse
 
rickdelpo1 profile image
Rick Delpo

Hi, nice article, I thought u might be interested in reading about my cloudfront migration, some gotchas they dont tell u about
click below at
dev.to/rickdelpo1/cloudfront-dns-m...

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay