Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 asset resources from static domain or subdomain

I am trying to optimize my project to avoid send cookies with the static resources (i.e: images, scripts, stylesheets, etc). My approach is to create a static.my-domain.com domain to serve from there all the static resources without cookies.

How can I load the resources from this domain using Symfony2 using asset?

I am using Symfony 2.1 RC2

like image 516
unairoldan Avatar asked Sep 01 '12 15:09

unairoldan


2 Answers

Turns out there's an assets_base_urls options that allows you to set assets domains.

like image 159
meze Avatar answered Nov 07 '22 01:11

meze


I added some twig globals to deal with this

# config.yml
framework:
    templating:
        engines: ['twig']
        assets_version: 'dev'
        assets_version_format: "%%2$s/%%1$s"
    session:
        cookie_domain:        %session.cookie_domain%
twig:
    globals:
        assets_version: dev
        static_assets_base_url: %static_assets_base_url%
        static_images_base_url: %static_images_base_url%
        static_image: %static_images_base_url%/dev/ # I didn't know how to reference the assets_version, so this is the same value
        static_content: %static_images_base_url%/

# parameters.yml
parameters:
    session.cookie_domain: .myapp.dev
    static_assets_base_url: http://myapp-static.dev
    static_images_base_url: http://myapp-static.dev/path/to/web
  • For versioned and compiled css/js etc I print {{ static_assets_base_url ~ asset_url }}.
  • For versioned images etc I print {{ static_image ~ 'bundles/mybundle/img/icon.jpg' }}.
  • For non-versioned images etc I print {{ static_content ~ 'content/img/upload-123.jpg' }}.

I don't remember exactly why I did this, but it was related to assetic bugs (what a surprise). It just can't handle paths correctly, like sometimes it doesn't add the version, or it does it wrongly.

It will be a pain if you have to modify the assets version manually, so you better have a deployment script ready to do this.

Oh and remember that Assetic won't dump the compiled assets in the specified directories, this is a known issue. So you have to add your own symlinks for these directories.

EDIT

The 'session.cookie_domain' parameter lets you use the same domain and avoid cookies, if your app is in a subdomain. If your app is not using a subdomain, you will have to use a separate domain for the static assets.

like image 1
ChocoDeveloper Avatar answered Nov 07 '22 02:11

ChocoDeveloper