简体   繁体   中英

How to specify multiple path patterns for a CloudFront Behavior?

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 ?

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
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM