2

I have uploaded my HUGO static site into AWS S3 Bucket. I have also added the domain in cloudrfront.

The home index.html page works fine, but I cannot access my resources. For example https://www.example.com works fine, but I cannot access https://www.example.com/posts/. I have to redirect links to the html file every time.

On localhost https://www.example.com/posts/ displays automatically the page ( without redirecting https://www.example.com/posts/ to https://www.example.com/posts/index.html.

Is there some property in cloudfront or Amazon S3 to replicate the behaviour of localhost and not have to change the links of the site?

workaround
  • 131
  • 1
  • 5

2 Answers2

4

CloudFront does not actually have this feature. You can redirect the root object https://www.example.com/ to https://www.example.com/index.html by setting DefaultRootObject, but there's nothing for subdirectories such as https://www.example.com/posts/.

However, you can run arbitrary code on CloudFront using Lambda@Edge or CloudFront Functions, so it's possible for us to add this feature ourselves. With the "origin request" trigger we can rewrite the request to S3, changing /posts/ to /posts/index.html. https://github.com/CloudUnder/lambda-edge-nice-urls has some good handling of paths that works well with Hugo. The Amazon documentation has an example of how you can do the same thing with CloudFront Functions.

Another option is to enable uglyurls in your config so that all links within you site have index.html hardcoded in to them.

user2640621
  • 1,405
  • 9
  • 20
0

For CFN (CloudFormation) users:

Look for

    Type: AWS::CloudFront::Distribution

Replace

        Origins:
          - DomainName: example.s3-website-ap-southeast-2.amazonaws.com
            Id: example
            S3OriginConfig:
              OriginAccessIdentity: ""
            OriginAccessControlId: !GetAtt CloudFrontOriginAccessControl.Id

with

        Origins:
          - DomainName: example.s3-website-ap-southeast-2.amazonaws.com
            Id: example
            CustomOriginConfig:
              OriginProtocolPolicy: http-only

Also, you need to open your bucket read permission:

  BucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      Bucket: example
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal: "*"
            Action: s3:GetObject
            Resource: arn:aws:s3:::example/*

enter image description here enter image description here

Official documents:

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-origin.html#cfn-cloudfront-distribution-origin-customoriginconfig

https://docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteAccessPermissionsReqd.html

Teemo
  • 101