Why Is Setting Up a CDN for Static Files Critical?
When it comes to website loading speed, static files (images, CSS, JavaScript, fonts, and videos) typically account for more than 70% of the total page size. If you serve these files directly from your origin server, every user request goes to your data center—even if the user is on the other side of the world. The result? High latency, excessive bandwidth consumption, and poor user experience.
Setting up a CDN (Content Delivery Network) solves this problem: static files are copied to multiple servers around the world, and user requests are routed to the nearest server (PoP). However, the key point is that simply enabling a CDN is not enough; if you don't configure caching and content invalidation correctly, your users will see outdated versions of files, or the cache won't work properly. In this article, we'll walk through setting up a CDN from start to finish, focusing on domain connection, cache configuration, and invalidating old content.
Step 1: Choosing the Architecture and Connecting the Domain to the CDN
Before anything else, you need to decide whether your main domain (e.g., example.com) should point directly to the CDN or whether you should use a separate subdomain (such as cdn.example.com). For static files, the best practice is to use a separate subdomain—because you can control cache settings independently from the main domain and quickly disable the CDN if issues arise.
Connecting the Domain via a CNAME Record
After creating a CDN (e.g., on Cloudflare, Fastly, or ServerNet's CDN service), add a CNAME record to your DNS:
cdn.example.com. CNAME your-cdn-endpoint.example.net.
If your CDN provides a static IP address (as some services do), use an A record instead of a CNAME:
cdn.example.com. A 203.0.113.10
Important note: If you're using a CNAME record, make sure to set the TTL to a low value (e.g., 300 seconds) so that changes to the endpoint are applied quickly.
Configuring SSL and HTTPS
To avoid mixed content errors, be sure to enable SSL on the CDN subdomain. If your CDN issues certificates automatically (like Let's Encrypt), simply enable the SSL/TLS option in the panel. Otherwise, upload the certificate manually. After enabling it, test that https://cdn.example.com responds correctly.
Step 2: Configuring Cache for Static Files
Cache configuration is the heart of CDN setup. If you don't configure caching correctly, the CDN will just be a regular proxy and won't add any speed. There are two levels of caching: browser cache (via HTTP headers) and CDN cache (at the PoP level).
Configuring Cache-Control and Expires
For static files that don't change (such as logos, fonts), you can set a long-term cache:
Cache-Control: public, max-age=31536000, immutable
This header tells the browser and CDN to cache the file for one year, and because it's immutable, the browser won't even send a revalidation request. For files that may change (such as main CSS or JS), use a shorter value:
Cache-Control: public, max-age=3600, must-revalidate
On your web server (e.g., Nginx), you can set these headers as follows:
location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg|woff2?)$ {
expires 1y;
add_header Cache-Control "public, immutable";
add_header CDN-Cache-Control "public, max-age=31536000";
}
Note that the CDN-Cache-Control header is CDN-specific and allows you to configure the CDN cache independently from the browser cache. This is very useful; for example, you might want the browser to cache a file for 1 day, but the CDN to hold it for 1 year.
Configuring Cache in the CDN Panel
In your CDN panel, create a rule for static file extensions. These rules typically look like this:
- Path pattern:
/*.css,/*.js,/*.png - Cache TTL: 30 days or 1 year
- Cache behavior: Cache everything (even if it has a query string)
A common mistake is setting the cache to Cache only if query string is empty. This causes files requested with ?v=2 to not be cached and to go back to the origin server. For static files, it's better to enable the Ignore query string option.
Step 3: Invalidating Old Content (Cache Purge)
The biggest challenge after setting up a CDN is cache invalidation. When you change a CSS file, if the old cache is still present on the PoPs, users will see the previous version. There are three main methods for this:
Method 1: Manual Purge from the Panel
Most CDNs have a Purge or Clear Cache button in their panel. You can purge a specific URL or the entire domain. This method is good for emergencies, but it's not suitable for frequent deployments.
Method 2: Purge via API
The best method for automation is using the API. For example, on Cloudflare, you send the following request:
curl -X POST "https://api.cloudflare.com/client/v4/zones/{zone_id}/purge_cache" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{"files":["https://cdn.example.com/css/style.css"]}'
This request only purges the specified file. If you want to purge everything, use {"purge_everything":true}. In your deployment script (e.g., in CI/CD), call this API after uploading new files.
Method 3: Using Cache Busting (File Renaming)
Instead of purging the cache, you can rename the file. For example, instead of style.css, use style.abc123.css. This is done automatically by tools like Webpack or Vite. The advantage of this method is that you don't need to purge, and old files will gradually expire from the cache. But the downsides: it increases the storage space used on the CDN, and if you delete old files from the server, old links (which are indexed in pages) may return 404 errors.
Common Mistake: Forgetting Versioning in HTML
Many developers only purge the cache but forget that the user's browser still has the old HTML version that links to the old file. Solution: In your HTML, add the file version manually or automatically:
<link rel="stylesheet" href="https://cdn.example.com/css/style.css?v=20250601">
If you're using Cache Busting with file hashes, this problem is solved automatically.
Step 4: Monitoring and Troubleshooting
After setting up the CDN, you need to make sure everything is working correctly. Here are some tools and techniques:
Checking Response Headers
You can check the headers of a file with the following command:
curl -I https://cdn.example.com/css/style.css
In the output, look for these items:
cache-status: HIT(meaning the file was served from the CDN cache)age: 12345(how long the file has been in the cache)x-cache: HIT(on some CDNs)
If you see MISS, it means the file came from the origin server and wasn't cached. This usually indicates that the cache headers aren't configured correctly.
Testing from Different Locations
Use tools like ping or online services (such as check-host.net) to ensure that requests from different parts of the world go to the nearest PoP. If all requests go to a single IP, your DNS is probably not configured correctly, or your CDN doesn't have enough PoPs.
Troubleshooting 502 and 504 Errors
If you see 502 or 504 errors after setting up the CDN, the issue is usually with the connection between the CDN and the origin server. Check the following:
- Does the origin server only allow connections from specific IPs? (Check the firewall)
- Is the origin server's SSL valid? (If the CDN can't verify SSL, it will return an error)
- Does your hosting have a limit on concurrent connections? (CDNs open many connections)
Summary and Best Practices
Setting up a CDN for static files isn't just a simple configuration; it's a process that includes domain connection, precise cache configuration, and invalidation management. Here's a summary of key points:
- Use a separate subdomain (
cdn.example.com). - Set the
Cache-Controlheader withimmutablefor immutable files. - Use
CDN-Cache-Controlto separate browser and CDN caching. - For frequent deployments, integrate API-based Purge into your CI/CD.
- Use Cache Busting with file hashes to reduce the need for purging.
- Always check response headers with
curl -Iafter changes.
If you're looking for an integrated solution, CDN services offered by cloud hosting providers like ServerNet typically have these features ready-made, and you can use these settings without infrastructure hassle. But it's important to understand the concepts in this article so you can properly manage any CDN.
Finally, remember that setting up a CDN isn't a one-time task; it requires continuous monitoring and reconfiguration based on user behavior and changes to your site. By following the tips above, you can significantly increase your site's speed and create a better experience for your users.