I have a vanity URL that I want to redirect to a specific page in a website(Cloudfront Distribution). I can do a redirect with Masking from GoDaddy but it does not help me with https options for the vanity URL. So I was thinking of doing this using Lambda function triggered on Viewer Request section of the CF distribution. I am using the following code for the Lambda function, can anyone let me know what I am doing wrong as I am getting an error from CF side-
import json
def lambda_handler(event, context):
request = event['Records'][0]['cf']['request']
response = {
'status': '301',
'statusDescription': 'Moved Permanently',
'headers': {
'location': [{
'key': 'Location',
'value': 'https://cf-distribution/page/'
}]
}
}
return response
I tried this lambda Function and was expecting it to redirect with masking to the page in CF distribution but it gives me an error, will post the error soon.
I would recommend CloudFront Functions over Lambda@Edge: it's designed for this type of use case and is both simpler and more cost effective. Here's an example of a conditional 301 redirect—you can edit as needed.
You can create the function in the Functions section of the CloudFront console then attach it to one or more cache behaviors for the distributions where you want this redirect to be used.
function handler(event) {
var request = event.request;
var host = request.headers.host.value;
if (host === 'www.example.com') {
var response = {
statusCode: 301,
statusDescription: 'Moved Permanently',
headers: {
'location': { "value": `https://example.com${request.uri}` }
}
};
return response;
}
return request;
}