Using a CDN with Symfony2

Craig Blanchette on Google+ on March 8th 2013

Sometimes you may want to store your assets in a separate location to improve speeds, and to also retrieve assets from a cookie-less domain which search engines seem to prefer. You can easily set this up through the Framework configuration in your Symfony2 project:

app/config/config.yml
  1. framework:
  2.   templating:
  3.   packages:
  4.   cdn:
  5.   base_urls:
  6.   http: ['http://cdn.mysite.com']
  7.  
  8.   cdn2:
  9.   base_urls:
  10.   http: ['http://cdn2.mysite.com']

Once you've done this you can just add a second argument to your asset functions:

  1. <img src="{{ asset('some-image.jpg', 'cdn') }}">
  2. <img src="{{ asset('some-other-image.jpg', 'cdn2') }}">

This will end up giving you an image pointing to "http://cdn.mysite.com/some-image.jpg"