5

I have a CloudFront distribution with an s3 origin and a custom origin. I would like all traffic on /api/* and /admin/* to go to the custom origin, and all other traffic to go to the s3 origin. Currently I have it working with only /api/*:

                cloudfront.SourceConfiguration(
                    custom_origin_source=cloudfront.CustomOriginConfig(
                        domain_name=alb,
                        origin_protocol_policy=cloudfront.OriginProtocolPolicy.MATCH_VIEWER,
                    ),
                    behaviors=[
                        cloudfront.Behavior(
                            allowed_methods=cloudfront.CloudFrontAllowedMethods.ALL,
                            path_pattern="/api/*",
                            forwarded_values={
                                "headers": ["*"],
                                "cookies": {"forward": "all"},
                                "query_string": True,
                            },
                        )
                    ],
                ),

I could probably repeat the behavior with /api/*, but I will eventually have some additional paths to add that will need to be routed to the custom origin (ALB), so I'm wondering if there is a way to do this that is more DRY.

Does path_pattern accept /{api,admin,other}/* style patterns? Or should I refactor the Behaviors section to reuse allowed_methods and forwarded_values and then repeat multiple behaviors with a different path_pattern?

1 Answer 1

6

Does path_pattern accept /{api,admin,other}/* style patterns?

No, this pattern style is not supported based on the documentation.

should I refactor?

Yes, you can simply save all the path_pattern corresponding to this custom origin into a list, say path_patterns. Then use a simple handy Python list comprehension,

behaviors=[
    cloudfront.Behavior(
        allowed_methods=cloudfront.CloudFrontAllowedMethods.ALL,
        path_pattern=pp,
        forwarded_values={
            "headers": ["*"],
            "cookies": {"forward": "all"},
            "query_string": True,
        },
    ) for pp in path_patterns
]
Sign up to request clarification or add additional context in comments.

1 Comment

Note also that the default limit to the number of cache behaviors (and therefore path patterns) per distribution is 25 but AWS Support can bump this up on request, to a value as high as 250 if needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.