Integrate CloudwaysCDN with Laravel

A Content Delivery Network (CDN) is an arrangement of intermediary servers hosted at server farms located all over the web. The goal of a CDN is to deliver content as fast as possible regardless of the location of the server hosting the website. In technical terms, CDN delivers web caching, load balancing, and request routing to ensure fast page load speed.

How CDN Adds Value to Your Business

Regardless of the nature of your business, CDN adds value to your website. If you are into services delivery, a CDN ensures faster delivery of your services to the clients. Similarly, if you are a product or a platform, a CDN allows all visitors and users enjoy your product without experiencing lag.

In all cases, a CDN is an important addition to the website and business processes. The high page load speed that a CDN delivers ensures that the visitors are able to access your services and product offerings faster (often resulting in more conversions).

A CDN works by storing a copy of the website’s static content and serving it to the clients. This means that the request from the client is fulfilled not by the original server but by the closest CDN server. This results in fast page load speed as the data is served from the closests CDN server.

In order to facilitate the customers, Cloudways has launched CloudwaysCDN to make sure that all Laravel applications could ensure a great UX for the users. In this article, I will show you how easy it is to integrate Cloudways CDN with your Laravel applications.

For the purpose of this article, I assume that you have a Laravel application deployed on a Cloudways managed Laravel web hosting. If that is not the case with you, I strongly urge you to give Cloudways a try. Just sign up for a trail and then follow the following GIF for server and application setup.

CDN Request Flow

Here’s how a CDN works with your website. The URL of all static assets on your website is replaced with a CDN URL. For instance: http://mywebsite.com/img/logo.png becomes http://cdn.mycdnprovider.com/img/logo.png. In this context, the file logo.png will be served from the CDN server, rather than the original server hosting the file.

There are two ways a CDN brings in data from your website into its network. The first way is the manual method in which the records are transferred manually. In the second method, the content is brought in automatically. In both these methods, the CDN continues to point to the website assets until the linking is changed. In such cases, CDN generally takes care of the refreshing the link.

I will begin with demonstrating the simple process of enabling CloudwaysCDN for your Laravel applications.

Enable CloudwaysCDN for the Laravel Application

Start by clicking the CloudwaysCDN option available at the end of the Application Management options. In the screen that opens, When you click the tab, you will see the CDN configuration screen. Here you will find the URL of the application to be inserted in the WEBSITE URL field and click the Create button.

Next, you will get the newly generated URL for the Laravel application:

Few things to note here:

  • You can view the bandwidth usage on this screen.
  • You can purge old content from the CDN cache using the Purge button.
  • You can remove your subscription anytime

Integrate CloudwaysCDN with Laravel Application

Create the ./app/helpers.php file and update the ./composer.json as follow

“autoload”: {
“classmap”: [
],
“files”: [
“app/helpers.php”
]
},

To actualize Laravel CDN, make a worldwide capacity which will be utilized all through the application. For this, include a helpers.php record in the application envelope. Place the accompanying code in the record.Execute the command composer dump-autoload to dump the autoloader then add the following code to your ./app/helpers.php.

<?php
// global CDN link helper function
function cdn( $asset ){
// Verify if KeyCDN URLs are present in the config file
if( !Config::get(‘app.cdn’) )
return asset( $asset );
// Get file name incl extension and CDN URLs
$cdns = Config::get(‘app.cdn’);
$assetName = basename( $asset );
// Remove query string
$assetName = explode(“?”, $assetName);
$assetName = $assetName[0];
// Select the CDN URL based on the extension
foreach( $cdns as $cdn => $types ) {
if( preg_match(‘/^.*.(‘ . $types . ‘)$/i’, $assetName) )
return cdnPath($cdn, $asset);
}
// In case of no match use the last in the array
end($cdns);
return cdnPath( key( $cdns ) , $asset);
}
function cdnPath($cdn, $asset) {
return “//” . rtrim($cdn, “/”) . “/” . ltrim( $asset, “/”);
}

The standard asset() function will be called if no CDN URLs are defined in the ./config/app.php config file.

Set URL

Now, open app/config/app.php or the config file for your environment. Add your CDN domain into the app.php, just like the below example:

‘cdn’ => [
“77728–356013-raikfcquaxqncofqfm.stackpathdns.com” => “css|js|eot|woff|ttf,jpg|jpeg|png|gif|svg”
],

That’s it. Everything is setup. Simply replace the asset() function in the views with the new cdn() function. For example, I have used the following code to link the bootstrap.css file

<link rel=”stylesheet” href=”{{ cdn(‘css/bootstrap.css’) }}”>

Global Helper

Use the global helper function in your views:

<img src=”{{ cdn( “/img/yourImg.png” ) }}” alt=”Your Image loaded from KeyCDN” />

Example of using CDN for image:

<img class=”img-responsive” src=”{{cdn(‘images/iphone.png’)}}” alt=”iphone”>

Replace all the asset() functions with cdn() in your files and improve the performance of your application dramatically.

Conclusion

The key ideas to setup a CDN that is configurable and viable are:

  • Utilize a worldwide variable to effectively get to the URL of your CDN
  • Prefix the URLs of your static assets with the CDN variable
  • Utilize setup records to characterize the CDN variable
  • Set your CDN to get assets from an inception server
  • Negate your assets by placing them into a formed registry
  • Satire the formed registry by utilizing a URL Rewrite
  • Keep up a rendition number inside a config record

Having CDN offers your application stack to acquire various advantages in terms of execution and server loads. A CDN enables you to store particular records/archives that don’t change frequently and even documents that change each once in while. This will lessen the IO activities that you application server needs to deal with and additionally diminish the transfer speed utilized. For clients that means better execution.

Cloudways have partnered with StackPath (formerly known as MaxCDN), and provides 1-Click activation for the CloudwaysCDN. Note that, for a single website, the monthly subscription costs $1 per 25GB of bandwidth.


Integrate CloudwaysCDN with Laravel was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: