Redirect www to non-www in CloudFront
23 Jul 2025If 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:
- Attach this Lambda@Edge function at the viewer-request event.
- It ensures canonical URLs and avoids duplicate content issues.
- Improves SEO by redirecting
wwwtraffic consistently to the apex domain.