Redirection and custom HTTP headers using CloudFront

AWS CloudFront can be used for many things. For example it’s a very convenient way of doing redirects and similar HTTP operations. On 2021-05-03 Amazon introduced a new concept called CloudFront Functions, which means that you can define custom operations without the need for Lambda@Edge.

Instead of spinning up Caddy or Nginx, you can handle this kind of stuff directly in CloudFront. Once you get the hang of it, it’s very straight-forward. You can get a lot done with a few lines of JavaScript. I.e. “serverless computing”, as some like to call it.

Here’s an example on how to perform redirection and setting Strict-Transport-Security:

function handler(event) {
  // This is a viewer request function.

  var destination_site = '';
  var h = {};

  h['strict-transport-security'] = {
    value: 'max-age=300; includeSubdomains',

  h['location'] = {
    value: destination_site + event.request.uri,

  var response = {
    statusCode: 301,
    statusDescription: 'Moved Permanently',
    headers: h,

  return response;

View the function as raw text

Author: Carl Winbäck
Published: 2021-07-11
Last modified: 2021-08-18

Back to the main page