Search code examples
amazon-web-servicesamazon-s3amazon-ec2amazon-cloudfront

How to prevent user from accessing the non http version of my site?


I currently have my nodejs server in docker compose served on EC2 instance and my react app served on s3, both of them are behind two cloudfront distributions respectively.

I am fairly new to these AWS products, I would like to know how to config this AWS setup so when users access the original domains provided by s3 and EC2 (http), they would get redirected back to the cloudfront ones (https)?


Solution

  • The method of protection depends on the origin.

    For S3 origins, you can disable access entirely by making sure the bucket is not public. You can use an Origin access identity for for cloudfront to authenticate cloudfront against the bucket. This way people can onl reach the s3 origin via cloudfront.

    For EC2's behind a load balancer (I assume you use an ALB as it is best practice) the setup is slightly trickier. You can add a "secret" header in the call cloudfront makes to your ALB (e.g. x-origin-protection). Then add a listener rule to your alb that forwards only when the header is present and a default action of being redirected to cloudfront.

    Example listener rule:

    ListenerRule:
      Type: AWS::ElasticLoadBalancingV2::ListenerRule
      Properties:
        Actions:
          - Type: forward
            TargetGroupArn: !Ref MyEc2InstanceTargetGroup
        Conditions:
          - Field: http-header
            HttpHeaderConfig:
              HttpHeaderName: x-origin-protection
              Values:
                - !Ref SecurityToken
        ListenerArn: !Ref HttpsAppListener
        Priority: 1
    

    For a more complete guide on the setup for ALB, check https://www.arhs-group.com/protecting-aws-alb-behind-aws-cloudfront-distribution/