Reputation: 3073
I am serving HTTP request from Amazon CloudFront using Amazon S3 to store the file. The S3 bucket is set as Website Hosting enabled. The index document is index.html
.
When I search on Google, I see both these URLs:
{url}/index.html
{url}/
Both of these URLs serve the same content.
How can I set it up such that {url}/index.html
performs a code 301 Moved Permanently to {url}/
?
Upvotes: 4
Views: 5272
Reputation: 5858
Two options, with different levels of complexity:
Use a <link>
tag to tell Google what's the canonical URL for a given document:
<link rel="canonical" href="https://example.com/">
You can use a simple Lambda function deployed to CloudFront's edge servers. Follow this tutorial, and the function body you want (Node.js 8.10) is:
exports.handler = (event, context, callback) => {
const { request } = event.Records[0].cf;
const isIndex = request.uri.endsWith('/index.html');
if (isIndex) {
const withoutIndex = request.uri.replace(/\/index\.html$/, '');
callback(null, redirect(withoutIndex));
} else
callback(null, request);
};
function redirect(url) {
return {
status: '301',
statusDescription: 'Moved Permanently',
headers: {
location: [{
key: 'Location',
value: url
}]
}
};
}
Upvotes: 2
Reputation: 5392
Ideally if it is static content there is no redirect need the way you asked...
You could have config in such a way that if user requests for {url}/ then redirect cloud front to serve {url}/index.html but not other way...
Ref: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/DefaultRootObject.html
Upvotes: 0