exports.handler = async (event) => {
const request = event.Records[0].cf.request;
const requestUri = request.uri;
// Path mapping logic:
const pathMappings = {
"/": "/featuretoggle/uk", // Redirect root path to /featuretoggle/uk
"/old-path": "/new-path", // Add more path mappings as needed
};
const targetUri = pathMappings[requestUri] || requestUri; // Redirect to mapped path if present, otherwise use original path
if (targetUri !== requestUri) {
const response = {
status: '301',
statusDescription: 'Moved Permanently',
headers: {
'location': [{
key: 'Location',
value: targetUri,
}],
},
};
return response;
} else {
return request; // Pass through request without modification if no redirect needed
}
};
Key points:
- Path Mappings: Customize the
pathMappings
object to define your specific URL redirection rules. - 301 Status Code: The
301
status code signals a permanent redirect to search engines and browsers. - Location Header: The
Location
header specifies the target URL for the redirect. - Pass-through: If no path mapping matches, the request is passed through without modification.
Remember:
- Deploy this code as a Cloud Function on AWS.
- Configure CloudFront to trigger the Cloud Function for appropriate events (e.g., viewer request).
- Test thoroughly to ensure redirects work as expected.