Skip to content

Instantly share code, notes, and snippets.

@pangui
Created December 1, 2023 22:36
Show Gist options
  • Save pangui/c58949a565b6fc631e68263b59ca1bd8 to your computer and use it in GitHub Desktop.
Save pangui/c58949a565b6fc631e68263b59ca1bd8 to your computer and use it in GitHub Desktop.
Redirect non-www to www url in AWS CloudFront
// Create function in
// cloudfront /
// functions
// Create distribution in
// cloudfront /
// distributions
// Associate function to distribution in
// cloudfront /
// distributions /
// YOUR_DIST /
// behaviors /
// new behavior /
// function associations /
// viewer request
function handler(event) {
const request = event.request;
const headers = request.headers;
// Check if the request is for www.example.com
if (headers.host && headers.host.value.startsWith('www.')) {
// Redirect to non-www URL
const redirectUrl = 'https://' + headers.host.value.replace(/^www\./, '') + request.uri;
// Create a 301 (permanent) redirect response
const response = {
statusCode: 301,
statusDescription: 'Moved Permanently',
headers: {
"location": { "value": redirectUrl }
}
};
// Return the response to perform the redirect
return response;
}
// If the request is not for www.example.com, continue as normal
return request;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment