问题
I am trying to write an nginx config that will handle two sites on both http and https, it seems to work as long as a client never visits both sites, but if they do there are caching/cross-site issues.
# Allow cross origin
location ~* \.(eot|svg|ttf|woff|woff2|json)$ {
if ($http_origin ~* (https?://(admin\.)?example\.com(:[0-9]+)?)) {
add_header 'Access-Control-Allow-Origin' "$http_origin";
}
}
So if I load example.com, everything works, but then when I load admin.example.com I get issues like this
(index):1 XMLHttpRequest cannot load http://origin.example.com/js/data-lib/currency.json. The 'Access-Control-Allow-Origin' header has a value 'http:// example . com' that is not equal to the supplied origin. Origin 'http:// admin . example . com' is therefore not allowed access.
As near as I can tell this is because the browser cached the original request with the header it came with, and now it's denying me even though another request from the server would allow it. The proof is if I check the Disable Cache in the Chrome Developer tools then the issue never happens.
How do I solve this issue? Is it possible to do multiple domains + ssl/http all in one config, or is it necessary to split this up based on the domain and protocol being requested?
(Sorry about the horrible spaces in my example, apparently StackOverflow thinks I'm trying to post links when I'm just writing examples)
回答1:
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.
At least it should have that effect in browsers to that conform to the relevant part of the HTTP spec.
So you could update your nginx config to do this:
# Allow cross origin
location ~* \.(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 request headers to decide whether a cached response can be used rather than requesting a fresh one from the origin server. It is used by the server to indicate which headers it used when selecting a representation of a resource in a content negotiation algorithm.
来源:https://stackoverflow.com/questions/46063304/nginx-ssl-cors-and-caching-of-access-control-allow-origin-value-cross-site