1

I am building an S3 URL redirect, nothing special just a bunch of zero-length objects with the WebsiteRedirectLocation meta filled out. The S3 bucket is set to server static websites, bucket policy set to public, etc. It works just fine.

HOWEVER - I also want to lock down certain files in the bucket - specifically some HTML files that serve to manage the redirects (like adding new redirects). With the traditional setup, I can both use the redirects, and also serve the HTML page just fine. But in order to lock it down, I need to use Cloudfront and Lambda@edge like in these posts:

https://douglasduhaime.com/posts/s3-lambda-auth.html

http://kynatro.com/blog/2018/01/03/a-step-by-step-guide-to-creating-a-password-protected-s3-bucket/

I have modified the lambda@edge script to only prompt for a password IF the admin page (or its assets like CSS/JS) are requested. If the requested path is something else (presumably a redirect file) the user is not prompted for a password. And yes, I could also set a behavior rule in Cloudfront to decide when to use the Lambda function to prompt for a password.

And it works kind of. When I follow these instructions and visit my site via the Cloudfront URL, I do indeed get prompted for a password when I goto the root of my site - the admin page. However, the redirects will not work. If I try to load a redirect the browser just downloads it instead.

Now, in another post someone suggested that I change my Cloudfront distribution endpoint to the S3 bucket WEBSITE endpoint - which I think also means changing the bucket policy back to website mode and the public which sucks because now its accessible outside of the Cloudfront policy which I do not want. Additionally - Cloudfront no longer automatically serves the specified index file, which isn't the worst thing.

SO - is it possible to lock down my bucket, the server it entirely through Cloudfront with Lambda@edge BUT also have Cloudfront respect those redirects instead of just prompting a download? Is there a setting in Cloudfront to respect the headers? Should I set up different behavior rules for the different files (HTML vs redirects)?

Dinesh Kumar
  • 484
  • 3
  • 15
rugbert
  • 9,753
  • 9
  • 35
  • 60

1 Answers1

0

Instead of using the WebsiteRedirectLocation meta, which is specific to S3 static website hosting and has no effect when Cloudfront is the server, replace your empty objects with HTML objects that contain a meta HTML tag with the desired redirect target:

<meta http-equiv="Refresh" content="0; url=https://www.example.com" />

The number before the semicolon is the delay before the redirect, in seconds, where 0 is immediate.

Don't forget to also change the Content-Type meta tag of the objects to text/html.

And if you want to support old browsers that might not handle the Refresh directive correctly, add an anchor link as explained here.

Yigal
  • 1,170
  • 9
  • 22