I have been using S3 to host my images and delivering them using AWS CloudFront. But recently I faced an issue whiling accessing those images via a CORS request.
I tried many solutions available for the same but couldn’t get the issue to fix. Here I am sharing the configuration that I had to do in AWS to fix the issue.
Update S3 bucket CORS configuration
Go to you S3 bucket > Permissions > CORS Configuration and add the following in the CORS configuration editor:
<?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>HEAD</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration>
Enable CloudFront to forward headers for CORS requests
If you want CloudFront to respect cross-origin resource sharing settings, configure CloudFront to forward the
Origin header to your origin. Go to your CloudFront and select your Distribution then go to Behaviors > select Behavior and click on Edit.
On Edit page you have to go to Cache Based on Selected Request Headers and click on Whitelist to whitelist the following headers .
To whitelist a header, select the header name from left box and click on Add to move it to the right box.
Click on Yes, Edit to save the configuration.
Now you will have to wait for ~10-20 minutes or until you Distribution status changes from In Progress to Deployed.
Test CORS request to CloudFront urls
You can test if your configuration for CORS was successful by going to site: Test CORS.
Hope this helps. Let me know if you face any issue in comments.