我使用Nginx来使用这个问题中概述的技术来响应CORS请求提供静态文件。 但是,当文件不存在时,404响应不包含Access-Control-Allow-Origin: *
头,浏览器也是如此。
如何发送Access-Control-Allow-Origin: *
在404响应?
即使这是很久以前问的,我正在编译nginx更多的模块,但与新版本的nginx,我发现我不必自定义编译nginx,我所需要的只是添加always
指令。
http://nginx.org/en/docs/http/ngx_http_headers_module.html
Syntax: add_header name value [always];
如果指定了always参数(1.7.5),则无论响应代码如何,标题字段都将被添加。
所以一个调整版本的CORS头文件:
if ($cors = "trueget") { # Tells the browser this origin may make cross-origin requests # (Here, we echo the requesting origin, which matched the whitelist.) add_header 'Access-Control-Allow-Origin' "$http_origin" always; # Tells the browser it may show the response, when XmlHttpRequest.withCredentials=true. add_header 'Access-Control-Allow-Credentials' 'true' always; }
我假设你正在使用add_header
指令。 该文档注意到这只能设置200,204,301,302和304状态码的标题。 要为404状态代码设置标题,您需要使用headers_more模块中的more_set_headers
指令(您可能需要重新编译nginx才能获得此模块)。 以下内容将设置所有状态码的标题:
more_set_headers 'Access-Control-Allow-Origin: *';
您也可以将其限制为特定的状态码:
more_set_headers -s '404' 'Access-Control-Allow-Origin: *';