By default, CloudFront distribution URLs (eg. https://d2kl2vxl3xne45.cloudfront.net) are publicly accessible. So if you are using CloudFront to serve a static website out of S3, for example, then your site shall also be accessible via the CF URL as well as any custom domain you are using. If you are using Signed URLs or Signed Cookies to restrict access to your content then this is not an issue, but if you are serving your content publicly then it might bother you.
I am not sure if CloudFront URLs are easily discoverable (probably not) but if we want to ensure that our web application cannot be accessed via the CF URL then we need to block access to it.
AWS Docs Tutorial: Create a simple function with CloudFront Functions
WAF - an alternative solution may be to use AWS WAF custom rules (assuming you are using WAF that is). You would also only probably want to explore this option if you are using WAF at the CloudFront edge rather than on your Load Balancers.
-
Go to CloudFront in the console and choose Functions > Create Function. Note that a function exists outside the scope of any distributions so you don't create them under any specific distribution - this allows any generic functions to be used across multiple distributions.
-
Enter the following function.
function handler(event) { var request = event.request; var host = request.headers.host.value; if (host.includes('cloudfront.net')) { return { statusCode: 403, statusDescription: 'Forbidden', headers: { 'content-type': { value: 'application/xml' } }, body: { 'encoding': 'text', 'data': '<?xml version="1.0" encoding="UTF-8"?><Error> <Code>AccessDenied</Code><Message>Access Denied</Message></Error>' } }; } return request; }
Note that the
body
contains XML but we could have set thecontent-type
to betext/html
and returned a HTML body. The XML body in our version above mimics the forbidden page that AWS natively presents when you try and access a forbidden resource so it looks more native. -
Save changes.
-
Now Publish > Publish function.
-
Now Associated distributions > Add association.
- Choose the distribution, and Event type: Viewer Request, Cache behaviour: Default.
- Add association.
-
The associated distribution will automatically redeploy. Wait a few minutes for the redeployment to complete before testing.
-
Now try and request the CF distribution directly and you should see the response sent by the function - https://d2kl2vxl3xne45.cloudfront.net/
A note on function updates
If you update a function you only have to republish it to make the changes live, you do not need to redeploy any associated distributions.