I’m trying do something like below for HTTP 301 redirect, so that web users will redirect to different news pages.
if ((request.uri == "/news") || (request.uri == "/news/") && (request.origin.domainName == "sub.mydomain.com")) { const redirectResponse = { status: '301', statusDescription: 'Moved Permanently', headers: { 'location': [{ key: 'Location', value: '/local-news/', }], 'cache-control': [{ key: 'Cache-Control', value: "max-age=3600" }], }, }; callback(null, redirectResponse); }
However, seems like this request.origin.domainName == “mydomain.com” part is not working in my function. Is this correct way to pick the domain name which client coming from?
I think this request.origin.domainName method will not work as Origin Object support only for Origin requests. Is there any possibility, that I can get the domain name which client coming from for the Viewer requests?
The reason I need this is, I’ve multiple domains, that users access the same CloudFront distribution. Hence, when user coming from different domains, user must be redirected to different news sites.
Can anyone support me on this?
Advertisement
Answer
If you want to get distribution Domain Name
const distributionDomain = event.Records[0].cf.config.distributionDomainName;
The more information You can find in AWS Documentation
Also, check
accessing origin URL from AWS lambda@edge
Also, try this way
'use strict'; exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response; const request = event.Records[0].cf.request; const hostHeader = request.headers['host'][0].value; callback(null, response); };
hostHeader
should be the CNAME(domain name)
The more info here