Use Azure CDN Custom Origin for items in Sitecore media library

Using a CDN can significantly improve loading times of your site as static resources like images can be retrieved from it. A CDN has many edge servers and will automatically serve the resource from the closest location to the user. Additionally they will decrease the load on the webserver as it does not need to serve the resource to individual users.

Last year Azure announced custom origin support in their CDN. Before that you could only use the CDN from a limited set of Azure services in your Azure subscription like the Cloud Service that hosted your Sitecore environment. I have seen some complicated solutions to have the CDN use Sitecore. This was especially complicated if the cloud service hosted multiple Sitecore instances. Using the CDN is much easier with this new policy. This post will describe the steps involved in setting this up.

The first step is to set up the Azure CDN with custom origin, use the URL of your Sitecore site as the origin URL. This can be done either on the new or classic Azure Portal, see screenshots below:

custom-origin-new-portal
Classic portal:
custom-origin-blog

When the CDN is created it will generate a URL for it, something like http://az123456.vo.msecnd.net/ It is also possible to map a custom domain to this endpoint see here

Now the CDN is ready to use and you can retrieve any media library item, for example if your image has a URL of http://mysitecoresite.com/-/media/images/image.png then you can load it now from http://az123456.vo.msecnd.net/-/media/images/image.png

The CDN is now ready to use however the CDN edge servers will not cache the image but instead return it from the origin which is the Sitecore server. This is because by default Sitecore sets cache-control to private which causes the CDN not to cache it. This has to be changed to public in the Sitecore settings:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <settings>
      <setting name="MediaResponse.Cacheability">
        <patch:attribute name="value">public</patch:attribute>
      </setting>
    </settings>
  </sitecore>
</configuration>

Now static resources will be cached by Azure’s CDN edge servers so site will load faster for your users.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s