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?
CodePudding user response:
Go to your Cloudfront Distribiution
you want to create a custom error page.
- Then in the CloudFront Management Console choose
Error Responses
- Click on the Create Custom Error Response button to get started, then create the error response.
- 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.
CodePudding user response:
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.