IAnswerable

Redirect www to non-www in CloudFront

23 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 what happens on each request:

sequenceDiagram
    participant Viewer
    participant CloudFront
    participant Lambda as LambdaAtEdge
    Viewer->>CloudFront: GET www.example.com
    CloudFront->>Lambda: viewer-request event
    Lambda-->>CloudFront: 301 to example.com
    CloudFront-->>Viewer: 301 Moved Permanently
    Viewer->>CloudFront: GET example.com
  

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: