rupps
rupps

Reputation: 9907

How to generate a 404 page from a CloudFront Function?

I would like to generate a 404 page from a Cloudfront Function for some well-known paths. So far I am able to generate the 404 response with the enclosed pseudo code, but without any body. The documentation suggests it is possible, but there are no examples around.

function handler(event) {
    
    // NOTE: This example function is for a viewer request event trigger. 
    // Choose viewer request for event trigger when you associate this function with a distribution. 
    var request = event.request, response = event.response;
    
   
    if (URL_IS_FORBIDDEN) {
        return {
            statusCode: 404,
            statusDescription: "Not Found",
        };
    } else  {
        return request;
    }     
}

If I try to assign body or text, cloudfront says the property does not exist, and indeed it is not mentioned in the docs.

So can I output a body from the cloudfront function?

Upvotes: 0

Views: 3315

Answers (2)

Tricky
Tricky

Reputation: 7165

Rather than returning a 404 response directly from CloudFront – which will skip your configured Error Page – you can return one indirectly by forcing your origin to return a 403/404. This will trigger CloudFront to return the specified Error Page as it would for any other missing resource.

This is achieved by using a CloudFront function to rewrite your restricted resource to a resource on the origin that is known not to exist:

function handler(event) {
    var request = event.request;
    
    // Route the request to a resource which is known not to exist.
    if (URL_IS_FORBIDDEN) {
        // NULL doesn't exist at the origin, so it will 403/404.
        request.uri = '/NULL';
    } 
    return request;
}

Now, the response from CloudFront should include a status code of 403/404 (or whatever you've set up your CloudFront behavior to forward).

Upvotes: 0

Cristian
Cristian

Reputation: 1714

You can't currently return a response body from a CloudFront Function (see below). But you can either 1/ Use a Lambda@Edge function, or 2/ Override the request URI to point to the 404 URL at your origin.

For number 2, if your 404 file is located at /pages/404.html at your origin (e.g., on S3), you could use a CloudFront Function like this:

function handler(event) {
    var request = event.request;
    
    // Route the request to a 404 page if the URL is not found.
    if (URL_IS_FORBIDDEN) {
        request.uri = '/pages/404.html';
    } 
    return request;
}

When you modify an HTTP response with CloudFront Functions, you cannot alter or modify the response body. If you need to alter the response body, use Lambda@Edge. With Lambda@Edge, you can replace the entire response body with a new one, or remove the response body.

https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/writing-function-code.html

Upvotes: 1

Related Questions