Optimized media serving in Umbraco by creating media CDN

Reduce bandwidth with serving from one domain

  • Share

Let's say you have multiple websites with different domains in one Umbraco instance. All websites will use the same media, but the catch is how will it serve them.

For example the same image will be served to a browser with two different paths like the following:

  • domain1.com/media/12345/image.jpg
  • domain2.com/media/12345/image.jpg
  • domain3.com/media/12345/image.jpg

Your browser does not know that this is the same image and neither your proxy does, so each image is loaded as a totaly different file which will cause your server to process separate request for each image request.

The idea is to serve the same image from the same domain, so you can use one of the websites as your CDN provider by registering additional hostname to it like cdn.domain1.com

Now all you have to do is to serve images in html with the absolute url pointing to cdn.domain1.com.

Luckily in Umbraco when you fetch media item and get value of url property you get relative path for example /media/12345/image.jpg

We can easily concat CDN domain to this string value and every image will be server from cdn.domain1.com. The cdn domain we can store in web.config so it can be easily changed when moving website from one environment to another.

string cdnImagePath = string.Concat(System.Configuration.ConfigurationManager.AppSettings["MediaDomain"],Umbraco.TypedMedia("1235").Url);

To make this more easy to use, we can make it as an extension method for IPublishedContent type as following

        public static string GetCdnMedia(this IPublishedContent media)
            return string.Concat(System.Configuration.ConfigurationManager.AppSettings["MediaDomain"], media.Url);

And just invoke it in razor view

string cdnImagePath = Umbraco.TypedMedia("1235").GetCdnMedia();

However, you will not see some major differences in your bandwidth if you do not have some large amount of media to serve, but still I think it is a good practice to apply to websites in Umbraco which hosts more than one website on different domains.


  • Share


Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.

Comments for this article

comments powered by Disqus