Skip to main content

Command Palette

Search for a command to run...

How to Use AWS CloudFront for Image Redirection to Default Images

Learn how to serve a default image using CloudFront if you get a 404 from your origin server.

Updated
•3 min read•View as Markdown
How to Use AWS CloudFront for Image Redirection to Default Images

In this blog, we'll explore how to use AWS CloudFront to serve a default image when your origin returns a 404 error. By implementing a Lambda@Edge function, we can ensure that users always receive a placeholder image instead of a broken link.

Why Redirect Images on 404?

When a requested image is missing, returning a 404 error can lead to a poor user experience. Redirecting to a default image ensures that your website remains visually consistent and user-friendly.

Setting Up AWS CloudFront with Lambda@Edge

Step 1: Create a CloudFront Distribution

First, create a CloudFront distribution that points to your origin server where your images are hosted. Ensure that your distribution is properly configured to handle the necessary requests.

Step 2: Write the Lambda@Edge Function

The core of this solution involves using a Lambda@Edge function triggered on the Origin Response event. This function checks the status code from the origin and redirects to a default image if a 404 error is detected.

Here’s a breakdown of the code:

def lambda_handler(event, context):
    response = event['Records'][0]['cf']['response']
    response_headers = response['headers']

    if response['status'] == '404':
        if 'transfer-encoding' in response_headers:
            return {
                'status': '302',
                'headers': {
                    'location': [{
                        'key': 'Location',
                        'value': "DEFAULT-IMAGE-URL"
                    }],
                    'transfer-encoding': [{
                        'key': 'Transfer-Encoding',
                        'value': 'chunked'
                    }]
                }
            }
        else:
            return {
                'status': '302',
                'headers': {
                    'location': [{
                        'key': 'Location',
                        'value': "DEFAULT-IMAGE-URL"
                    }]
                }
            }
    return response

Code Explanation

  1. Event Trigger: The function is triggered on the Origin Response event.

  2. Status Check: It checks if the response status code is 404.

  3. Transfer-Encoding Handling: If the Transfer-Encoding header is present, it includes it in the redirection response to prevent any CloudFront validation errors.

  4. Redirection: If a 404 is detected, it redirects to the specified default image URL.

Step 3: Deploy the Lambda@Edge Function

  1. Create the Lambda Function: Go to the AWS Lambda console and create a new function.

  2. Set Permissions: Ensure the function has the necessary permissions to execute.

  3. Attach to CloudFront: In the CloudFront distribution settings, attach the Lambda@Edge function to the Origin Response event.

Step 4: Test the Configuration

After deployment, test the configuration by requesting an image that doesn’t exist on your origin. You should be redirected to the default image.

Step 5: Monitor and Optimize

Monitor your CloudFront logs to ensure that redirections occur as expected and optimize the Lambda function as necessary to handle additional scenarios.

Conclusion

By implementing a Lambda@Edge function with AWS CloudFront, you can efficiently handle missing images by redirecting to a default placeholder. This enhances the user experience and maintains the integrity of your website’s design.

Key Takeaways:

  • Use Lambda@Edge: To customize content delivery behavior at the edge.

  • Handle 404 Errors Gracefully: Redirect users to a default image.

  • Maintain Transfer-Encoding: To prevent CloudFront validation errors.

By following these steps, you’ll ensure a seamless experience for your users, even when images are missing. Happy coding!