-1

I have an AWS S3 bucket that contains images and a default.png image. All images are public, but I want the user to get the default.png when they try to access an image that does not exist. e.g. .../non_exist.png

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

I found something that sounds relevant, but the documentation is very poor that it only tells that there exist such function, but not how to do it.

How can I set a default image whenever the user tries to access an image that is not in the bucket?

Thanks!

Dawn17
  • 7,825
  • 16
  • 57
  • 118

3 Answers3

2

From the Documentation you want to set up a Redirect for an HTTP error.

https://docs.aws.amazon.com/AmazonS3/latest/dev/how-to-page-redirect.html#advanced-conditional-redirects

Example 3: Redirect for an HTTP error

Suppose that when a requested object is not found, you want to redirect requests to an Amazon Elastic Compute Cloud (Amazon EC2) instance. Add a redirection rule so that when an HTTP status code 404 (Not Found) is returned, the site visitor is redirected to an Amazon EC2 instance that handles the request. The following example also inserts the object key prefix report-404/ in the redirect. For example, if you request a page ExamplePage.html and it results in an HTTP 404 error, the request is redirected to a page report-404/ExamplePage.html on the specified Amazon EC2 instance. If there is no routing rule and the HTTP error 404 occurs, the error document that is specified in the configuration is returned.

Example routing rule one the S3 bucket.

  <RoutingRules>
<RoutingRule>
<Condition>
  <HttpErrorCodeReturnedEquals>403</HttpErrorCodeReturnedEquals >
</Condition>
<Redirect>
  <ReplaceKeyWith>default.png</ReplaceKeyWith>
</Redirect>
</RoutingRule>

strongjz
  • 4,271
  • 1
  • 17
  • 27
  • 1
    The appropriate code to match with this rule is `403` rather than `404` unless the bucket allows public *listing* of objects (which is usually not something you would want to allow). Not sure why the documentation doesn't seem to mention it. https://stackoverflow.com/a/24001725/1695906 – Michael - sqlbot Nov 17 '19 at 01:21
0

When s3 is configured for website hosting, you can configure 404 custom document destination to a URL. Here you can specify the default.png.

My solution to this problem would be as below: Configure the aws cloudfront and s3 bucket as a origin to it. Configure the lambda@edge to this cloudfront, where you can programmatically check if image exists or not, if not return the default image for all requests which are 404.

Aws cloudfront will help you cache the images at edge locations as well.

Rishikesh Darandale
  • 3,222
  • 4
  • 17
  • 35
0

You can use cloudfront in front for S3 to add custom redirect errors pages. For example, see this screenshot below where I have /error.html for any request where images not found in the bucket.

enter image description here

Vikash Rathee
  • 1,776
  • 2
  • 25
  • 43