Cloudfront (w/ S3) Static Website Doesn’t utilize index.html from sub directories

amazon s3amazon-cloudfrontamazon-web-services

I have my website hosted on S3 with CloudFront as a CDN, and I need these two URLs to behave the same and to serve the index.html file within the directory:

example.com/directory
example.com/directory/

The one with the / at the end incorrectly prompts the browser to download a zero byte file with a random hash for the name of the file. Without the slash it returns my 404 page.

How can I get both paths to deliver the index.html file within the directory?

If there's a way I'm "supposed" to do this, great! That's what I'm hoping for, but if not I'll probably try to use Lambda@Edge to do a redirect. I need that for some other situations anyway, so some instructions on how to do a 301 or 302 redirect from Lambda@Edge would be helpful too : )

Update (as per John Hanley's Comment)

curl -i https://www.example.com/directory/

HTTP/2 200 
content-type: application/x-directory
content-length: 0
date: Sat, 12 Jan 2019 22:07:47 GMT
last-modified: Wed, 31 Jan 2018 00:44:16 GMT
etag: "[id]"
accept-ranges: bytes
server: AmazonS3
x-cache: Miss from cloudfront
via: 1.1 [id].cloudfront.net (CloudFront)
x-amz-cf-id: [id]

Update

CloudFront has one behavior set, forwarding http to https and sending the requests to S3. I also has a 404 error route under the errors tab.

Best Answer

Have you tried accessing the directory directly on S3 without going through cloudfront — is the behaviour similar?

I actually Ensure all links to subdirectories ended with an explicit index.html to avoid the issue. The other option is storing each sub directory into its own bucket behind cloudfront — the index.html as default object is an S3 setting that ‘I think’ only applies to the root directory of the bucket.

A lambda@edge could rewrite the request instead of redirecting the user. i.e pretend Index.html every time a GET requests ends with /. But it’s not very elegant I’m afraid.

In any case for these serverless architectures , lambda@edge seems to be the place to our web server configurations we’d traditionally put into Nginx or Apache.

Related Topic