skip to Main Content

I’m getting 404 errors on a specific path pattern say xyz/index.html, how to return custom HTML content instead of a 404 Not Found error?

2

Answers


  1. Chosen as BEST ANSWER

    You can achieve this using CLoudfront Edge Functions:

    • Create lambda function in us-east-1 region (irrespective of your local region).
    • Update the function role Trusted Relationships to allow access for cloudfront.
      {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Principal": {
                    "Service": [
                        "edgelambda.amazonaws.com",
                        "lambda.amazonaws.com"
                    ]
                },
                "Action": "sts:AssumeRole"
            }
        ]
      }
      
    • Update the function code to handle the origin response.
      def lambda_handler(event, context):
        response = event['Records'][0]['cf']['response']
    
        is_404_page = int(response['status']) == 404
        
        is_html_page =  "index.html" in event['Records'][0]['cf']['request']["uri"]
    
        if is_404_page and is_html_page:
            response['status'] = 200
            response['statusDescription'] = 'OK'
            response['body'] = """
    <!DOCTYPE html>
    <html>
      <head>
        <title>Custom Response</title>
      </head>
      <body>
        <p>Custom response page.</p>
      </body>
    </html>
        """
    
        return response
    
    • Deploy Function.
    • Click on Actions -> Choose Deploy to Lambda@Edge under Capabilities
    • Configure the CloudFront trigger, and deploy it.
    • It takes around 5 minutes to update CloudFront distribution, then you can test your changes.

  2. Go to your Cloudfront Distribiution you want to create a custom error page.

    • Then in the CloudFront Management Console choose Error Responses

    enter image description here

    • Click on the Create Custom Error Response button to get started, then create the error response.

    enter image description here

    • You can also choose the HTTP status code that will be returned along with the response page.

    There’s a blog post on how to do it step by step here.

    Full documentation on generating custom error responses for Cloudfront is here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search