Categories
Blog

Getting a custom 404 document on Amazon CloudFront using S3


How to serve custom 404 error documents using Amazons CloudFront and an Amazon S3 bucket as its origin? The problem is: CF doesn’t let you assign custom error or index documents but S3’s website feature does.

So you might guess you’re good to go if you select the S3 bucket from CloudFront’s origin dropdown? Well, it won’t. You have to use a custom origin and use whatever your S3 bucket shows you as its endpoint in the “Website” properties, e.g. yourbucketname.s3-website-eu-west-1.amazonaws.com. This is the custom origin you’ll use while creating your CloudFront Distribution.

Before you do that, make sure the custom error and index documents work on the S3 side. Try opening a non-existent file and you should get the error document, which could even be an image – which was the requirement in my case.

If that’s working go ahead and create your CloudFront Distribution and remember not to select the bucket from the dropdown but use a custom origin even though it’s essentially the bucket you’d have selected from the dropdown.

If you select the bucket from the dropdown you’ll see the ugly XML error message with a http header like this:

# curl -I http://your-custom-url/doesnotexist
HTTP/1.0 403 Forbidden
x-amz-request-id: something
x-amz-id-2: somethingelse
Content-Type: application/xml
Date: Tue, 13 Dec 2011 16:46:55 GMT
Server: AmazonS3
X-Cache: Error from cloudfront
X-Amz-Cf-Id: somethingverylong
Via: 1.0 someurl.cloudfront.net:11180 (CloudFront), 1.0 someotherurl.cloudfront.net:11180 (CloudFront)
Connection: close

You notice the “403 Forbidden”? That should be a “404 Not Found”. if you use the custom origin it’ll look good and you get something like this:

# curl -I http://your-custom-url/doesnotexist
HTTP/1.0 404 Not Found
x-amz-error-code: NoSuchKey
x-amz-error-message: The specified key does not exist.
x-amz-error-detail-Key: doesnotexist
x-amz-request-id: something
x-amz-id-2: somethingelse
Date: Tue, 13 Dec 2011 17:40:54 GMT
Server: AmazonS3
X-Cache: Error from cloudfront
X-Amz-Cf-Id: somethingverylong
Via: 1.0 someurl.cloudfront.net:11180 (CloudFront), 1.0 someotherurl.cloudfront.net:11180 (CloudFront)
Connection: close

I’m not sure if this is a bug on Amazons end or if they do this on purpose. If anyone knows, let me know! Thanks to Joe Masters Emison on Quora for pointing me into the right direction.

Now, Amazon, how about adding better SSL support and letting us use our own (wildcard) certificates?