How to add and leverage CDN on your website

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...

If you have experience of working with web development, you know for sure that high speed is crucial. Speed matters a lot, and faster is considered to be better.

One safe strategy is CDN, or content delivery network. It’s very simple, as well: you don’t have to rewrite acodebase or edit your content. However, some of web developers overlook this opportunity thinking it’s hard to implement.

In fact, the process of CDN integration is not as challenging as it seems. When you have the things configured you will performance and Google PageSpeed soar, which also results into better search engine rankings, more satisfying revenue and customers’ loyalty. This article will guide you through the process of setting up a CDN to work on custom web applications and the tricks to be used to get most out of your work.

It should be noted that setting up a CDN may be even easier, if you work with CMS like WordPress where plugins can do all the work for you. However, let’s assume not everyone has this luxury and focus on a more traditional way.

Basics of CDN technology

It won’t hurt, if we review the basic concepts of what a CDN is, and how it works.

A content delivery network fetches static assets of your website form the original server and caches them on many different edge servers. When a browser requests to visit your website, the static content is served via CDN, and it makes transfer faster. Some content delivery networks are also optimized for delivery of dynamic objects like on-demand videos and streaming videos.

How does a browser know to get resources from a CDN instead of the original server? The URL addresses of your static resources are replaced to point that. For example, you want a CDN to be configured as a subdomain. For a website called Web-service that might be something like cdn.web-service.com – there will be the relative URL for which assets are based. The URLs of assets that initially look like:

http://www.web-service.com/image.jpg

http://www.web-service.com/style.css

http://www.wervice.com/script.js

…would become:

http://cdn. web-service.com/image.jpg

http://cdn. web-service.com/style.css

http://cdn. web-service.com/script.js

In this case, the browser will send the requests to your CDN instead of your server, taking a considerable load off your server and boosting your whole website.

Several servers for one website?

Yes, that’s true when you use a CDN, but that doesn’t mean that you actually have to manage two servers. Instead, you will use CDN as a virtual layer that’s placed between your server and visitor’s browser. This virtual layer gets insight into the request made by browser and responds with cached data on behalf of the server.

Sometimes you can also upload your assets directly to the CDN and take the whole load off your server. But the most advanced CDNs automatically fetch assets from your server and pre-cache them, so you don’t need to upload the files to different servers and manage them in different locations.

How to implement a CDN on a Custom Application?

There are hundreds of CDN solutions around, and they have slightly different processes of implementation. We will focus on the most widespread method of CDN leveraging and get to know how to set things up step by step.

1. Choose a CDN and Register Your Site
As soon as you’ve decided what CDN network you want to use for you web application, you need to register an account. As a rule, when registering a new account you need to set up a pull zone, or distribution. It will pull data automatically from the origin server you specify after the first request for the file. The files will be serves to end users either from a subdomian of your CDN, or a custom domain that points to the CDN – you choose that. The data that’s not necessary anymore will be automatically purged from a server after some customizable amount of time.

2. Create your CDN URL
CDN URL is the URL where all assets will be pointed as soon as you set everything up. The golden rule is to use an URL name that’s easy to search and replace on your database for all existing URLs. Like any other subdomain, it should be specified as a CNAME record in host’s DNS settings.

3. Refer Your Assets to the CDN
Now you need to create a variable for the CDN URL: it will be used to prepend the URL to your static resources. Why doing that? First, it will prevent mistakes in your markup. Secondly, it’s easier to maintain the URL, if you need to change it.

That can be done by defining a global CDN variable and then prepending this variable to URL addresses of static resources. The variable should be defined at both PHP level and JavaScript level: this way, you will have more flexibility further on. Besides, if you decide to cancel your CDN service, you will only need to replace the variables to get back to your original server.

This is the example of defining variables – the process can be slightly different in your case.

<?php

define(‘cdnURL’, ‘http://cdn.web-service.com/’);

?>

<html>

<head>

<title>We are here to help!</>

<script type=’text/javascript’>

/* Let’s define a javascript global for using the CDN inside scripts */

var cdnURL = ‘<?php echo cdnURL ?>’;

</script>

 

<link rel=’stylesheet’ href='<?php echo cdnURL ?>css/style.css’ />

</head>

<body>

<img src='<?php echo cdnURL ?>img/logo.png’ />

<button>Submit</button>

<script type=’text/javascript’ src='<?php echo cdnURL ?>js/main.js’></script>

</body>

</html>

Or, done in JavaScript:

(function() {

var preloadImage = document.createElement(‘img’);

preloadImage.src = cdnURL + ‘img/logo.png’;

})();

As a developer, you need to adjust to a slightly different process of setting things up: from now on, every static resource needs to get CDN URL variable prepended to it. The same applies to your CSS. You can setup a global CDN variable and prepend it to your CSS resources with the help of CSS preprocessor.

@cdnURL: ‘http://cdn.web-service.com/’;

button {

background-image: url(‘@{cdnURL}img/button.png’);

&:hover {

background-image: url(‘@{cdnURL}img/button_hover.png’);

}

}

In case with SaaS:

 

$cdnURL: ‘http://cdn.web-service.com/’;

button {

background-image: url(‘#{$cdnURL}img/button.png’);

&:hover {

background-image: url(‘#{$cdnURL}img/button_hover.png’);

}

}

The best thing about that is that you can simply switch of CDN off by setting CDN URL to / that will recreate all relative URLs. If you want to switch CDN URL, you just need to alter cdnURL.

Therefore, setting up a CDN is a 3-step process: you just link it to your server and point your assets to it so that CDN could serve assets when they’re requested.

What about advanced settings?

Now you know that setting CDN up isn’t such a complicated process. Now when you’ve undergone the main challenges, you can experiment with advanced settings and optimize the way your assets are delivered.

TimeToLive (TTL)
CDNs usually have a TimeToLive (TTL) set for files: this feature tells the CDN when the fresh copy of content should be retrieved. The longer the TTL is, the longer a version of this asset will stay in edge servers and continue to be delivered. The shorter the TTL is, the more often its version will be ditched and replaced by the same updated file from the original server.

Invalidating assets
TTL is convenient, but not perfect: if you update a file on your server, the change will not reflect in the website until the TTL expires and CDN retrieves the updated version of the copy. That can be overcome by invalidating the asset. You need to change the filename on the update, if the filename is changed, CDN just reads the newly named file as a new asset instead of updating the existing one.

For instance, this: http://cdn.web-service.com/image100.jpg

…will be replaced by something like this: http://cdn.web-service.com/image101.jpg

Leverage TTL for version control

Turns out, if the CDN holds onto one version of asset, and there’s a fresh copy of it placed on server but not fetched yet, we have two variations of the same asset. That can used to create “version control”, so updating our assets on server won’t mean that we automatically lose them – we can revert to a past copy.

There are two ways to do that: a complicated one, and a bit of cheating. The first method presupposes renaming all of your resources every time you make a change (we did the same when invalidating the asset). However, this is a real headache from maintenance standpoint. Let’s do some cheating instead.

Place your static assets into their own folders so that this: http://cdn.web-service.com/image.jpg

…becomes: http://cdn.web-service.com/img100/image.jpg

To invalidate the file and make your CDN to deliver the latest version, you should modify the subdirectory path like this: http://cdn.web-service.com/img101/image.jpg

That’s the trick: the filename stays the same, but now it’s placed in the directory on the server. The CDN is not aware of the difference, so it regards it as a completely new file. You’ve just created a new form of version control that’s directly in the folder.

But there’s no limit for perfection.

Changing the number of a folder after every update is still a tiresome process – there’s another sly step for maintaining your website. What you can do instead is make minor changes to the website’s .htaccess file. You can outsmart the CDN by serving all assets from the same folder, but make it seem being delivered from a versioned older due to rewrite rules.

<IfModule mod_rewrite.c>

RewriteEngine On

RewriteBase /

RewriteRule ^ver-[0-9]+.[0-9]+.[0-9]+(.*)$ $1 [L,NC]

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.*)$ index.php?/$1 [QSA,L]

</IfModule>

Now your server spoofs the version number in the URL while delivering the example image.jpg from the same path on the server where it was initially uploaded.

Invalidation of all assets on demand
Another useful thing you can do is to integrate version control trick into HTML markup so that CDN refreshed all assets as soon as you want to invalidate them totally. You need to set up a config file where you specify a variable for the version number, import this variable into your asset structure and alter the version number every time you want to push the refresh of files.

That’s what it’ll look like in a PHP config file:

 

VERSION

1.0.0

 

Configure::load(‘cdn’);

define(‘VERSION’, file_get_contents(APP.DS.”Config”.DS.”VERSION”));

define(‘CDN’, Configure::read(‘CDN.path’).VERSION.’/’); /* the trailing slash is important */

It will look the following wat in LESS config file:

@VERSION: ‘1.0.0’;

 

@import ‘cdn’;

@import ‘version’;

@CDNURL: ‘@{CDN}@{VERSION}/’;

 

button {

background-image: url(‘@{CDNURL}img/button.png’);

&:hover {

background-image: url(‘@{CDNURL}img/button_hover.png’);

}

}

You can also select to use the CDN variable as a file, environment variable, or what will be more suitable for you. The principles are similar: you’ll incorporate the CDN URL together with version number into all external resources.

Setting up a CDN may seem to be a hard task, and advanced settings can make you get lost in the jungle of coding. However, most of us need to know the basics of the initial setup. When you manage to implement a CDN, its benefits will become evident: better performance and user experience are guaranteed.

The process gets even simpler, if you manage website content with a popular CMS like WordPress, because there are many handy plugins for that.

Vadim Kolchev

52 publications

Vadim has graduated from Moscow Institute of Entrepreneurship and Law as finance and credit specialist. Prior to starting to work in hosting business directly, he occupied various roles in several companies, including but not limited to banking sphere and sports. As of 2015 he works for INXY Holding, with SpaceCDN being a vital part of the hosting branch of its business. Being tech enthusiast, he has started writing articles about dedicated servers, CDN, storage solutions and other hosting services long ago, and since then accumulated a lot of experience and knowledge in the field. Building hosting sales and support departments from scratch has added even more experience and knowledge and allowed to see the business from the inside and build required expertise. Now Vadim is CPO and COO of a successful hosting business. Having several important interviews and publications at platforms such as Hosting Journalist and Forbes, he continues to share knowledge about this branch of technology that has become not only his job but also a passion.

Learn more about us
in social networks