AWS CloudFront redirecting to S3 bucket

Rajneesh picture Rajneesh · Aug 3, 2016 · Viewed 24.3k times · Source

I have created a CloudFront distribution to serve the static website. S3 is origin server. Now if we access CloudFront URL, it redirects to S3 location.

d2s18t7gwlicql.cloudfront.net or test.telekha.in

In the browser it is showing https://telekha-test-www.s3.ap-south-1.amazonaws.com/index.html#/dashboard

I am expecting https://test.telekha.in/#/dashboard

If I access https://test.telekha.in through curl it returns my index.html document

If I access http://test.telekha.in through curl it returns

<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>CloudFront</center>
</body>
</html>

But in browser both HTTP and HTTPS are redirecting to https://telekha-test-www.s3.ap-south-1.amazonaws.com/index.html#/

Please let me know how to resolve this issue.

Answer

Slava Fomin II picture Slava Fomin II · Oct 17, 2019

Quick Solution

Use the regional domain name of your S3 bucket to configure the CloudFront distribution's origin, e.g.: {bucket-name}.s3.{region}.amazonaws.com.


Explanation

According to the discussion on AWS Developer Forums: Cloudfront domain redirects to S3 Origin URL, it takes time for DNS records to be created and propagated for newly created S3 buckets. The issue is not visible for buckets created in US East (N. Virginia) region, because this region is the default one (fallback).

Each S3 bucket has two domain names, one global and one regional, i.e:

  • global{bucket-name}.s3.amazonaws.com
  • regional{bucket-name}.s3.{region}.amazonaws.com

If you configure your CloudFront distribution to use the global domain name, you will probably encounter this issue, due to the fact that DNS configuration takes time.

However, you could use the regional domain name in your origin configuration to escape this DNS issue in the first place.


CloudFormation Template

If you are using CloudFormation, you can use the RegionalDomainName output attribute of the AWS::S3::Bucket resource:

S3Bucket:
  Type: AWS::S3::Bucket

CloudFrontDistribution:
  Type: AWS::CloudFront::Distribution
  Properties:
    DistributionConfig:
      Origins:
        - DomainName: !GetAtt S3Bucket.RegionalDomainName

More information

As well, I would highly recommend to read this blog post on the future of S3 different path formats: