4

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}/?

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
Anon21
  • 2,961
  • 6
  • 37
  • 46

2 Answers2

2

Two options, with different levels of complexity:

Canonical URL

Use a <link> tag to tell Google what's the canonical URL for a given document:

<link rel="canonical" href="https://example.com/">

Redirect using Lambda@Edge

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
      }]
    }
  };
}
djanowski
  • 5,610
  • 1
  • 27
  • 17
0

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

Venkateswara Rao
  • 5,242
  • 1
  • 18
  • 13