1 réponse
- Le plus récent
- Le plus de votes
- La plupart des commentaires
1
AWS offers a couple of services that can help you achieve this efficiently: AWS Lambda@Edge and Amazon CloudFront. Create a CloudFront distribution for your S3 bucket. Customize CloudFront with Lambda@Edge:
- Write and deploy a Lambda function in a supported runtime (like Node.js or Python). The function should add the 'Access-Control-Allow-Origin' and other required headers to the responses from your S3 bucket.
- Associate this Lambda function with your CloudFront distribution, setting it to trigger on the 'Viewer Response' event. This ensures that the CORS headers are added just before the responses are sent to the client.
Here's a basic example of what the Lambda@Edge function code might look like in Python:
def lambda_handler(event, context): # Get the response from the origin response = event['Records'][0]['cf']['response'] headers = response['headers'] # Set CORS headers headers['Access-Control-Allow-Origin'] = [{'key': 'Access-Control-Allow-Origin', 'value': '*'}] headers['Access-Control-Allow-Methods'] = [{'key': 'Access-Control-Allow-Methods', 'value': 'GET, HEAD'}] headers['Access-Control-Allow-Headers'] = [{'key': 'Access-Control-Allow-Headers', 'value': '*'}] # Return the response to viewer return response
If this has answered your question or was helpful, accepting the answer would be greatly appreciated. Thank you!
Contenus pertinents
- demandé il y a un an
- demandé il y a 4 mois
- demandé il y a 7 mois
- AWS OFFICIELA mis à jour il y a 7 mois
- AWS OFFICIELA mis à jour il y a 3 ans
- AWS OFFICIELA mis à jour il y a 2 ans
Thanks, will take a look at doing exactly this.
You don't need Lambda@Edge. You can do this easily with AWS CloudFront, which supports appending CORS headers.
Create a new CloudFront distribution like Step 3 listed here: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/GettingStarted.SimpleDistribution.html
In the "Behaviors" section of your cloudfront distribution's settings, under "Response headers policy - optional" select "CORS-With_Preflight".
There were a bunch of edge cases to do with URLs with query parameters and getting cloudfront to forward them, but that's kinda separate.
I accepted your answer as correct (with this comment) rather than posting a new answer, because it at least got me moving down the path, which turned out to be a lot shorter than expected. Thank you!