Caching of Access-Control-Allow-Origin value cross-site Caching of Access-Control-Allow-Origin value cross-site nginx nginx

Caching of Access-Control-Allow-Origin value cross-site


If you add the Vary response header with the value Origin, that should have the effect of causing any browser to skip its cache and make a new network request when the value of the Origin request header is different from the Origin value of the request it cached from.

See the relevant part of the HTTP spec. So you could update your nginx config to do this:

# Allow cross originlocation ~* \.(eot|svg|ttf|woff|woff2|json)$ {    if ($http_origin ~* (https?://(admin\.)?example\.com(:[0-9]+)?)) {        add_header 'Access-Control-Allow-Origin' "$http_origin";        add_header 'Vary' "Origin";    }}

You can read up more in the MDN article on the Vary response header.

The Vary HTTP response header determines how to match future requestheaders to decide whether a cached response can be used rather thanrequesting a fresh one from the origin server. It is used by theserver to indicate which headers it used when selecting arepresentation of a resource in a content negotiation algorithm.

…and in the MDN Access-Control-Allow-Origin article’s CORS and caching section:

If the server sends a response with an Access-Control-Allow-Origin value that is an explicit origin (rather than the "*" wildcard), then the response should also include a Vary response header with the value Origin — to indicate to browsers that server responses can differ based on the value of the Origin request header.

…and in the Fetch spec itself:

If your requirements are more complicated than settingAccess-Control-Allow-Origin to * or a static origin, use the Vary: Origin response header.

If Vary is not used and a server is configured to send Access-Control-Allow-Origin for a certain resource only in response to a CORS request: When a user agent receives a response to a non-CORS request for that resource, the response will lack Access-Control-Allow-Origin and the user agent will cache that response. If the user agent then encounters a CORS request for the resource, it will use that cached response from the previous non-CORS request — without Access-Control-Allow-Origin.

But if Vary: Origin is used in the same scenario, it will cause the user agent to fetch a response that includes Access-Control-Allow-Origin, rather than using the cached response from the previous non-CORS request lacking Access-Control-Allow-Origin