nginx跨域之add_header说明

由于浏览器的安全限制,前端js代码无法直接访问不同域下的资源。只要协议域名端口有任何一个不同,都被当作是不同的域。

跨域的解决方案有很多,目前常用的方案是通过nginx代理服务器给返回的响应头添加cors跨域配置项来解决。以下为配置示例:

add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS';
add_header Access-Control-Allow-Credentials 'true';
add_header Access-Control-Allow-Headers 'DNT,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,token,Wecom-Cert,group,preview-user,X-Mx-ReqToken';

但关于add_header的使用,有一些注意事项,在此对nginx配置add_header进行说明:

Syntax:add_header name value [always];
Default:—
Context:http, server, location, if in location

Adds the specified field to a response header provided that the response code equals 200, 201 (1.3.10), 204, 206, 301, 302, 303, 304, 307 (1.1.16, 1.0.13), or 308 (1.13.0). Parameter value can contain variables.
There could be several add_header directives. These directives are inherited from the previous configuration level if and only if there are no add_header directives defined on the current level.
If the always parameter is specified (1.7.5), the header field will be added regardless of the response code.

意思也就是说只有在响应状态码成功时,add_header 指令才生效,并且当前《作用域》下没有 add_header 指令时,会向上层继承。

在使用过程中难免会遇到上级指令被覆盖的情况,如:

server {
    add_header x-name nginx;

    location / {
        root /path;
    }

    location /static/ {
        add_header x-name2 nginx2;
    }
}

当匹配到 / 时,由于 location / 中没有 add_header 指令,所以会继承 server 中的 x-name ,而当匹配到 /static/ 时,由于内容已经有 add_header 指令,则上层的 x-name 不会被继承,导致只会输出 x-name2 。

实际工作中往往前端需要捕获服务端异常响应,这时在nginx跨域add_header上加上always,使nginx对任何响应码生效。

具体请参考nginx官方文档:http://nginx.org/en/docs/http/ngx_http_headers_module.html

posted @ 2021-12-23 14:44  wangqingyong  阅读(7009)  评论(0编辑  收藏  举报