CORS (CORS)

Security

Cross-Origin Resource Sharing. A browser security mechanism that controls which domains can request resources from your CDN. Without proper CORS headers, browsers block cross-origin requests for fonts, API calls, and JavaScript modules.

Updated Mar 9, 2026

Full Explanation

CORS exists because browsers enforce the Same-Origin Policy: JavaScript on example.com can't fetch resources from cdn.example.com unless the CDN explicitly allows it. The CDN responds with Access-Control-Allow-Origin headers telling the browser which origins are permitted.

For CDNs, CORS causes two common problems. First, forgetting to set CORS headers on font files or API endpoints, causing silent failures in production. Second, caching CORS responses incorrectly. If the CDN caches a response with Access-Control-Allow-Origin: https://app1.com and then serves that cached response to a request from app2.com, the browser blocks it. You need the Vary: Origin header to cache different CORS responses per requesting origin.

For public CDN assets (images, CSS, JS), the simplest approach is Access-Control-Allow-Origin: *. For APIs with credentials, you need to echo back the specific origin and set Access-Control-Allow-Credentials: true.

Examples

Nginx CORS for CDN-hosted fonts and assets:

# Allow any origin for public static assets
location ~* \.(woff2?|ttf|eot|svg|css|js)$ {
    add_header Access-Control-Allow-Origin "*";
    add_header Access-Control-Allow-Methods "GET, OPTIONS";
    add_header Access-Control-Max-Age 86400;

    if ($request_method = OPTIONS) {
        return 204;
    }
}

# Specific origins for API (with Vary for caching)
location /api/ {
    set $cors_origin "";
    if ($http_origin ~* "^https://(app1|app2)\.example\.com$") {
        set $cors_origin $http_origin;
    }
    add_header Access-Control-Allow-Origin $cors_origin;
    add_header Vary Origin;
}

Video Explanation

Frequently Asked Questions

Cross-Origin Resource Sharing. A browser security mechanism that controls which domains can request resources from your CDN. Without proper CORS headers, browsers block cross-origin requests for fonts, API calls, and JavaScript modules.

Nginx CORS for CDN-hosted fonts and assets:

# Allow any origin for public static assets
location ~* \.(woff2?|ttf|eot|svg|css|js)$ {
    add_header Access-Control-Allow-Origin "*";
    add_header Access-Control-Allow-Methods "GET, OPTIONS";
    add_header Access-Control-Max-Age 86400;

    if ($request_method = OPTIONS) {
        return 204;
    }
}

# Specific origins for API (with Vary for caching)
location /api/ {
    set $cors_origin "";
    if ($http_origin ~* "^https://(app1|app2)\.example\.com$") {
        set $cors_origin $http_origin;
    }
    add_header Access-Control-Allow-Origin $cors_origin;
    add_header Vary Origin;
}

Related CDN concepts include:

  • Vary Header — A response header that tells caches which request headers should be included in the cache …