Why Use CDN in Symfony?
Symfony is a flexible and powerful PHP framework that enables developers to build robust web applications quickly. By integrating a CDN with Symfony, you can significantly speed up your site by offloading static assets like images, CSS, and JavaScript files to a network of distributed servers. This reduces the load on your web server and improves website performance by delivering content faster to users around the world. Using a CDN with Symfony helps enhance user experience, reduce latency, and ensure better scalability for high-traffic websites.
Before you start
- Before you take any steps please back up your files and database.
- In the following, we will integrate a CDN service using the CDN domain cdn.mycompany.com Please visit the Services/How-To section to obtain your CDN domain.
- To integrate a CDN service on https:// website the CDN service must have SSL enabled.
- If your website embeds custom fonts then please first enable CORS for them.
- Before you take any steps please make sure that your CDN domain is ready-to-use here.
Create CDN Static service
Please refer to Creating a CDN Static service for more details.
Enable CDN in Symfony
Define CDN in config
Add the following to Symfony's app/config/config.yml file.
Symfony 2.6
framework: templating: assets_base_urls: http: ['http://cdn.mycompany.com'] ssl: ['https://cdn.mycompany.com']
Symfony 2.7 and later
Starting from Symfony 2.7, you should use the assets configuration instead of templating.
framework: assets: base_urls: ['https://cdn.mycompany.com']
Use the asset helper in views
In your templates, you can use the asset helper to reference static assets.
{{ asset('image.jpeg') }}
will output
https://cdn.mycompany.com/image.jpeg
Notes
- View HTML source code of your web pages to verify that you are using CDN, you should see source attribute of your images, CSS, JavaScript, etc. beginning with your CDN domain.
- Don't see your CDN domain in the source code of your web pages? If your website is using any cache plug-in/mechanism then you might want to clear/flush its cache.
- Having trouble with custom fonts? Please refer to Using custom fonts with CDN - setting CORS for more details.
- Still having trouble? Check your CDN URLs using our content check tool or please refer to Debugging a CDN service for more hints.
- Can you improve this guide or write a new one for software we haven't covered? Help us expand our CDN integrations section and earn $50 in CDN credit! Contact us to contribute.