maecapozzi
maecapozzi

Reputation: 240

Static site hosted on S3 and Cloudfront root page routes to www.example.com/index.html, not www.example.com

I have a static site hosted on Amazon S3 and Cloudfront.Currently, when I go to my site, www.example.com, I get a 403. It's only when I go to www.example.com/index.html that I actually access my site. My desired behavior is that when I go to www.example.com, I see what I see when I go to www.example.com/index.html.

I've set up a bucket that we can call example.com, that contains all of my site's information. I also have another bucket (www.example.com) that redirects to example.com.

My domain points to Cloudfront, where I have a Cloudfront domain set. I think this is where the problem is. I have to go to /index.html from this domain to actually see the site.

How do I set this up so that when I go to www.example.com, I see what currently lives at www.example.com/index.html?

I have already set index.html as my bucket's Index document.

Upvotes: 1

Views: 424

Answers (3)

djanowski
djanowski

Reputation: 5858

CloudFront's default root object only works for the root of your domain. So a request to https://example.com will serve /index.html from S3, but a request to https://example.com/about-us will simply 404 (or 403, depending on permissions).

If you want to serve index.html from any directory, you need to deploy a Lambda@Edge function for the origin request. Follow this tutorial, and the function body you need (Node.js 8.10) is:

exports.handler = (event, context, callback) => {
  const { request }  = event.Records[0].cf;
  const parts        = request.uri.split('/');
  const lastPart     = parts[parts.length - 1];
  const hasExtension = lastPart.includes('.');

  if (!hasExtension) {
    const newURI = request.uri.replace(/\/?$/, '/index.html');
    request.uri = newURI;
  }

  return callback(null, request);
};

Upvotes: 1

EFeit
EFeit

Reputation: 2132

In the CloudFront general configuration settings make sure the default root object is set to index.html. As a best practice you should use an Origin Access Identifier to ensure your objects are only served through CloudFront.

Also make sure your origin is set properly to your S3 bucket and the folder that contains your site (if applicable).

Upvotes: 0

Matt Houser
Matt Houser

Reputation: 36073

When you setup your S3 bucket for static website hosting (with or without CloudFront), you can configure the bucket with an Index Document. The Index Document is sent to the client when the client makes a directory request.

For example, you want www.example.com/index.html to be served when the client goes to www.example.com.

To do this, set index.html as your bucket's Index Document.

https://docs.aws.amazon.com/AmazonS3/latest/dev/HostingWebsiteOnS3Setup.html

See Step 1, sub-step 3(b).

Upvotes: 0

Related Questions