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?
You can use Lambda functions to change CloudFront requests and responses at the following points: After CloudFront receives a request from a viewer (viewer request) Before CloudFront forwards the request to the origin (origin request) After CloudFront receives the response from the origin (origin response)
Now you can programmatically define the origin based on logic in your Lambda function. This enables you to route requests to different origins based on request attributes such as headers, query strings, and cookies.
Since the launch, we have seen customers using Lambda@Edge in a variety of ways: All of these uses provide a rich and personal experience by executing logic closer to your users. Example functions for those listed previously can be found in the Lambda@Edge Developer Guide.
To get started with Lambda@Edge, attach a Lambda function to the Origin Request trigger of your Amazon CloudFront distribution behavior. When a user views a page that isn’t cached in CloudFront, the associated behavior triggers, which provides you with the opportunity to modify the origin object in the request prior to routing to the origin.
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
Lambda@Edge Example Functions
Doc
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With