Symfony 2 and Content Delivery Networks

 
Symfony 2 and Content Delivery Networks
 

Recently we set up the latest build of our company website with a content delivery network. This is the process we went through to get it set up and tested.

Set up your CDN

The specific service you choose will dictate how this is set up but it will likely be along similar lines to this: set up the origin name as your domain (corvitadigital.com), then update your resource name (cdn.corvitadigital.com). You will then likely need to add the new sub domain to your DNS with the correct CNAME.

Setting up Symfony

This process is pretty straight forward, you just need to tell Symfony that for all assets displayed within the application, they are not relative urls.

So, you need to ensure that all of your images, css and javascript files are set up with the asset tag:

{{ asset('/bundles/corvitawebsite/css/corvita.css') }}

Rather than going through all of your code checking, there is a quick fix for testing if you have all of these covered, but we will come to that...

Next is setting up Symfony correctly. Given that we don't want our assets to be fetched within the dev environment long term, we will add the following to the production environment:

//app/config/config_prod.yml
framework:
...
    templating:
      assets_base_urls: http://cdn.corvitadigital.com

For the assets_base_urls field, we have entered a string here, but you can enter different values for http and ssl if required:

      assets_base_urls:
        http: [http://cdn.corvitadigital.com]
        ssl:  [https://cdn.corvitadigital.com]

It's important to remember that you don't need to worry about the urls in your css files, as these will be relative to the CDN so will get fetched from the correct location.

If you also want to combine Sonata Media Bundle with a CDN, set up the following:

//app/config/config_prod.yml
...
sonata_media:
    cdn:
        server:
            path: http://cdn.corvitadigital.com/uploads/media

Once all of this is in place, we have the CDN set up correctly on your site and you can press on with using it. How can we be sure that we covered off all of the assets we want to be stored remotely?

We had already deployed to our staging server so all of our resources were available in the CDN, meaning we needed to switch it off temporarily:

// /etc/hosts
// Create a black hole for cdn
0.0.0.0 cdn.corvitadigital.com

This is great (also good for testing how your site will com across without styles, the alternative is a text browser in that case) - it means we can see the site in its basest form, and if anything is styled, or an image is showing, then we've missed the {{asset()}} tag for it.

January
January