How to disable access to cloudfront via the *.cloudfront.net url?

I created an AOI to restrict access of the s3 bucket to public. So you can not access the s3 objects via the s3 endpoint but cloudfront can access all those objects and serve them.

I setup an Alternate Domain Names and add the SSL Certificate for this domain.

I setup route 53 with a A rule to alias cloudfront distribution

I can access the page using the Cloudfront public url (*.cloudfront.net) and mydomain.com

How can I remove the *.cloudfront.net access to my page? This should be possible because the only service that needs this url is route 53.


You can use Lambda@Edge Viewer Request trigger. This allows you to inspect the request before the cache is checked, and either allow processing to continue or to return a generated response.

So, you can check the referer and make sure the request coming from your domain.

'use strict';

exports.handler = (event, context, callback) => {

  // extract the request object
  const request = event.Records[0].cf.request;

  // extract the HTTP `Referer` header if present
  // otherwise an empty string to simplify the matching logic
  const referer = (request.headers['referer'] || [ { value: '' } ])[0].value;

  // verify that the referring page is yours
  // replace example.com with your domain
  // add other conditions with logical or ||
  if(referer.startsWith('https://example.com/') ||
     referer.startsWith('http://example.com/'))
  {
    // return control to CloudFront and allow the request to continue normally
    return callback(null,request);
  }

  // if we get here, the referring page is not yours.
  // generate a 403 Forbidden response
  // you can customize the body, but the size is limited to ~40 KB

  return callback(null, {
    status: '403',
    body: 'Access denied.',
    headers: {
      'cache-control': [{ key: 'Cache-Control', value: 'private, no-cache, no-store, max-age=0' }],
      'content-type': [{ key: 'Content-Type', value: 'text/plain' }],
    }
  });
};

For more info read the following pages:

https://stackoverflow.com/a/51006128/6619626

Generating HTTP Responses in Request Triggers

Updating HTTP Responses in Origin-Response Triggers

Finally, this article has a lot of valuable info

How to Prevent Hotlinking by Using AWS WAF, Amazon CloudFront, and Referer Checking


Much easier than Lamda@Edge would be just to configure an ACL to block each request containing the Host header with your cloudfront distribution url.

Configure AWS WAF / ACL