Search code examples
ruby-on-railsamazon-cloudfront

How to set up app to disallow Cloudfront from fetching anything?


I use rails 5.2 and cloudfront for assets

How to set up app to disallow Cloudfront from fetching anything except for assets?


Solution

  • CloudFront doesn't have an explicit way to "allow only" certain path prefixes, since they will ultimately match the default * cache behavior if they don't match any others, but there are several ways of working around this, depending on the level of sophistication and complexity that suits your taste... but all of them would start with this step:

    • create a new cache behavior using the desired path pattern, such as /assets/* and select your existing origin to handle these requests.

    At this point, CloudFront still works as before, it's just internally considering the asset requests to match one behavior and everything else to match the other.

    So, what we need next is something different for the "other."

    The simplest solution is to create a second Origin, using the Origin Domain Name invalid.invalid. This is a syntactically valid hostname that points to a nonexistent target (the .invalid TLD is reserved for such purposes).

    After creating this origin, edit your default cache behavior to use this new origin.

    With this change in place and propagated, CloudFront will process /assets/* requests as before, but will throw an error on any other path. (The error is 502 Bad Gateway, if I remember correctly).

    This accomplishes the simple purpose of blocking all other requests.

    If you want to be a bit more proactive, and actually redirect requests back to the main site, you can accomplish this by creating an empty bucket in S3, and select the "Redirect requests" option. In the "target bucket or domain" box, put your main web site hostname. Then take the "Endpoint" shown in the Static website hosting box and use that as your origin hostname in CloudFront, for the default cache behavior. Any requests that arrive at CloudFront (for other than /assets/* will receive a redirect back to the main site.

    This option may be the better option if your CDN has been inadvertently picked up by search engines, because the links will redirect back to the main site.