Sunday, May 22, 2016

Amazon CDN CORS problem in Rails App

Problem

Font from origin 'https://d1b5oz78c0udqh.cloudfront.net' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://rubyplus.com' is therefore not allowed access.

Solution

1. Point your subdomain to your AWS Cloudfront domain. Go to AWS Cloudfront control panel, select your Cloudfront distribution and enter your CDN subdomain into the Alternate Domain Names (CNAMEs) field. Something like cdn.myawesomeapp.com will do.

2. Create a CNAME for cdn.myawesomeapp.com pointing to sdf73n7ssa.cloudfront.net.

3. Test your new CDN domain by making sure assets served are from cloudfront.

curl -I http://cdn.myawesomeapp.com/assets/image.png

4. AWS supports SSL Server Name Indication (SNI). Upload your SSL certificate to AWS first.
   Install the AWS command line tool first (that’s easy). Once you have your AWS command line tool installed and configured with the AWS keys, you can upload your SSL certificate:
 
   aws iam upload-server-certificate --server-certificate-name my_certificate_name --certificate-body file://my_cert.crt --private-key file://my_key.key --certificate-chain file://intermediate_cert.pem --path /cloudfront/my_cert_name_here/
 
5. Head back to your CDN distribution on AWS Cloudfront and select “Custom SSL Certificate (stored in AWS IAM)” and “Only Clients that Support Server Name Indication (SNI)” options.  

6. Now you should be able to see your assets both on HTTP and HTTPS served from CDN. Test it with CURL:

curl -I https://cdn.myawesomeapp.com/assets/image.png

7. Change your config.action_controller.asset_host in your production.rb to //cdn.myawesomeapp.com

Reference

Cross Origin Resource Sharing (CORS) Blocked for Cloudfront in Rails

No comments:

Post a Comment