Cloudfront, EC2 and Relative URLs
Asked Answered
G

2

6

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?

Glossematics answered 19/3, 2013 at 15:19 Comment(0)
S
1

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.

Shaner answered 21/3, 2013 at 5:23 Comment(0)
V
0

If you want to leave everything as is, you could pass everything through cloudfront setting up your site as a custom origin. This can work pretty well if your site is mostly static.

If you do want to take advantage of cloudfront without sending everything through, you will need to update your relative urls to absolute ones. CSS files can keep relative urls as long as the css file is served via cloudfront.

Viscount answered 19/3, 2013 at 15:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.