Cloudfront, EC2, and Relative URLs

This is probably a simple question, but I can not find a direct answer anywhere.

My site is hosted on Amazon EC2.

I want to use Amazon Cloudfront to speed up the loading of images, Javascript and CSS on my site.

On my site, I used relative URLs to point to the images, Javascript, and CSS that are on my EC2 server.

So now, to take advantage of Cloudfront, do I need to change all my relative URLs to absolute URLs that point to Cloudfront, or will this be handled automatically by Amazon / EC2 / Cloudfront? Or maybe the best way to ask the question is: can I leave all my URLs as relative URLs and still take full advantage of Cloudfront?

+6
source share
2 answers

The short answer is no, your relative URLs will not work as expected on CloudFront - except for the case mentioned by Gio Hunt , which as soon as your page loads the CSS file, any relative URL inside the CSS file itself will be resolved for CloudFront, but this is probably not very useful in your case.

See this answer for a solution using SASS, which very closely matches what I have done in the past:

  • I used SASS - http://sass-lang.com
  • I have mixin cdn.scss with content like $ image_path: "/ images /";
  • Import this mix in sass @import style "cdn.scss"
  • Update image paths as such: background: url ($ image_path + "image.png");
  • When deploying, I change the $ image_path variable in mixin.scss and then re-run sass

You basically rebuild your CSS to use the base url CDN (CloudFront), creating a variable that all your pages respect. The difficulty associated with this will depend on how many links and files you need to change, but a simple search and replacement for relative paths is quite easy to accomplish.

Good luck.

+1
source

If you want to leave it as it is, you can transfer everything through the cloud-based configuration of your site as a custom source. This can work very well if your site is mostly static.

If you want to use the cloud without sending everything, you will need to update the relative URLs to absolute ones. CSS files can store relative URLs as long as the css file is served through the cloud interface.

0
source

All Articles