Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloudfront, EC2 and Relative URLs

This is probably a simple question, but I can't find a straightforward answer anywhere.

My website is hosted on Amazon EC2.

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

Throughout my site, I've used relative URLs to point to the images, Javascript and CSS that reside on my EC2 server.

So, now, in order to take advantage of Cloudfront, do I need to change all my relative URLs into absolute URLs which point to Cloudfront, or will this be handled automatically by Amazon/EC2/Cloudfront? Or, maybe a better way to ask the question is, can I leave all my URLs as relative URLs and still get all the advantages of Cloudfront?

like image 301
Gio Hunt Avatar asked Mar 19 '13 15:03

Gio Hunt


1 Answers

Short answer is no, your relative URLs will not work as expected on CloudFront - except for the case mentioned by Gio Hunt that once your page loads the CSS file, any relative url inside the CSS file itself will resolve to CloudFront, but this probably isn't very useful in your case.

See this answer for a solution using SASS that pretty closely matches what I've done in the past:

  • I used SASS - http://sass-lang.com
  • I have a mixin called cdn.scss with content like $image_path: "/images/";
  • Import that mixin in the sass style @import "cdn.scss"
  • Update image paths as such: background:url($image_path + "image.png");
  • On deployment I change the $image_path variable in the mixin.scss and then rerun sass

Basically you regenerate your CSS to use the CDN (CloudFront) base url by creating a variable that all your pages respect. The difficulty involved with doing this will depend on how many references and file you need to change, but a simple search and replace for relative paths is pretty easy to accomplish.

Good luck.

like image 177
Ryan Weir Avatar answered Oct 19 '22 19:10

Ryan Weir