Implementing Canonical URLs with CloudFront Functions: A Guide

AWS CloudFront Functions offers a lightweight and scalable solution for managing URL redirects and rewrites using JavaScript functions.

What is a Canonical URL?

A canonical URL is the preferred URL for accessing a webpage when multiple URLs can lead to the same content. This is important for avoiding duplicate content issues and ensuring search engines index the correct version of your pages.

For example, if your website is accessible via both https://www.example.com/page and https://example.com/page implementing a canonical URL ensures that search engines recognize one version as the authoritative source.

What are CloudFront Functions?

AWS CloudFront functions are JavaScript code snippets that execute at CloudFront edge locations in response to events. They provide a fast and efficient way to customize content delivery and handle various tasks such as URL redirects and cache manipulation.

Good use cases for CloudFront Functions

  • URL redirects and rewrites
  • Cache and header manipulation
  • Access control and authorization

Main CloudFront Functions limitations

  • No network or file system access
  • Very limited memory and execution time
  • Very small package size

Below is a simple example demonstrating how to create a CloudFront Function to redirect users to the canonical version of a webpage:

// Define which domain do we want to be the canonical one
var canonicalHost = www.example.com;

// Get the request object from the event
var request = event.request;

// Extract the host (domain) from the request object
var host = event.request.headers.host.value;

// Test if the request matches the canonical domain
if (host !== canonicalHost ) {
    // Make new url
    var target = 'https://' + canonicalHost + uri;

    // Adds the query string if there is one
    if (Object.keys(request.querystring).length > 0) {
        target = target + '?';
        for (var key in request.querystring) {
         if (!target.endsWith('?')) { target = target + '&'; }
             target = target + key + '=' + request.querystring[key].value;
            }
        }

 // Returns a response to CloudFront
    return {
        // Status code of 301 for permanent redirect
        statusCode: 301,
        statusDescription: 'Moved Permanently',
        // Location header to redirect the request to the canonical URL
        headers: {
           'location': { value: target }
        }
    };
}

References