Created
April 29, 2018 15:06
-
-
Save croesus/c1692dfc6bac5d4d84c063c1a894e099 to your computer and use it in GitHub Desktop.
CloudFront Edge Lambda redirect non-www to www
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
exports.handler = (event, context, callback) => { | |
// Extract the request from the CloudFront event that is sent to Lambda@Edge | |
var request = event.Records[0].cf.request; | |
var params = ''; | |
if(('querystring' in request) && (request.querystring.length>0)) { | |
params = '?'+request.querystring; | |
} | |
var miduri = request.uri.replace(/(\/[\w\-_]+)$/, '$1/'); | |
var newuri = "https://www.example.com" + miduri + params; | |
const response = { | |
status: '301', | |
statusDescription: 'Permanently moved', | |
headers: { | |
location: [{ | |
key: 'Location', | |
value: newuri | |
}] | |
} | |
}; | |
return callback(null, response); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you so much the new regex work perfect and helped me specially for media paths like www.mysite.de/robots.txt .
i have no idea why my domain shows up like this , but at the end i decided not to use this lambda edge function for my gatsby redirect from non-www to www , and its working as expected only by using cloudfront with http to https redirect and s3 bucket with static hosting and redirect to my www.site.de.
thanks again