IAnswerable

Redirect www to non-www in CloudFront

22 Jul 2025

If you want to redirect traffic from www.example.com to example.com using Amazon CloudFront, you’ll quickly discover CloudFront doesn’t support this out of the box.

The simple solution is to attach a Lambda@Edge function to the viewer-request event that detects requests to www. and issues a 301 redirect.

Here’s a quick example:

'use strict';

exports.handler = async (event) => {
  const request = event.Records[0].cf.request;
  const headers = request.headers;

  const hostHeader = headers['host'][0].value;
  if (hostHeader.startsWith('www.')) {
    const newHost = hostHeader.replace(/^www\./, '');
    const redirectUrl = `https://${newHost}${request.uri}`;
    return {
      status: '301',
      statusDescription: 'Moved Permanently',
      headers: {
        location: [{
          key: 'Location',
          value: redirectUrl,
        }],
      },
    };
  }

  return request;
};

Key points: