AWS CloudFront Returns Status Code 200 on 404.html page

If you have followed my Getting a blog running with Jekyll, GitHub Actions, AWS S3, and CloudFront post, among other things you will see an issue where if you manually go to the 404.html page, CloudFront will happily serve you the 404.html page with 200 OK status code. This not only is wrong, but also hurts SEO. I don’t care much about SEO but I still want to fix the problem.

A screenshot of the developer tools network tab that shows 404.html page with status code 200.
Showing the 404.html page with 200 status code

The solution is quite simple. Head over to CloudFront and Functions on the sidebar and click on Create function button.

A screenshot of the Functions page in AWS CloudFront
Viewing the Functions page in AWS CloudFront

Name your function to anything you want, I will name it Return404 and add a description A function that sets the response status to 404 and click Create function. As for the code, I will write the following:

1function handler(event) {
2    var response = event.response;
3    response.statusCode = 404;
4    response.statusDescription = 'Not Found';
5    return response;
6}

This is a function we can use as Viewer response function, it sets the response status code to 404. And since we will only use it for our 404.html page, we don’t need to touch the body or make any other changes than the statusCode and statusDescription.

After typing it in the Development box, click on Save changes and then go to the Publish tab and click on Publish function.

A screenshot of the publish dialog in AWS CloudFront Functions
Publishing a function in AWS CloudFront Functions

Then go to your CloudFront distribution and click on Behaviors tab and click on Create behavior button.

A screenshot of the Behaviors page in AWS CloudFront
Viewing the Behaviors page in AWS CloudFront

Change the following settings:

Path pattern: /404.html
Origin and origin groups: Your S3 origin
Viewer protocol policy: Redirect HTTP to HTTPS
Allowed HTTP methods: GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE
Response headers policy - optional: SecurityHeadersPolicy
Function associations - optional:
    Viewer response: CloudFront Functions -> Return404
A screenshot of the Behaviors page in AWS CloudFront after a behavior for /404.html is created
Creating /404.html behavior in AWS CloudFront

And click on Create behavior. If you have other behaviors, move /404.html behavior to the top. And now whenever you access your 404.html page, you should receive a 404 status code.

A screenshot of the developer tools network tab that shows 404.html page with status code 404.
Showing the 404.html page with 404 status code