公司安全人员发现有跨域问题。
解决方案
通过修改nginx配置即可。
不设置的话,Access-Control-Allow-Origin 默认是 *,表示不限制访问域。
location 添加白名单列表(然并卵)
在location模块中添加:
add_header 'Access-Control-Allow-Origin' 10.111.96.186;
add_header 'Access-Control-Allow-Origin' 10.111.96.187;
add_header 'Access-Control-Allow-Origin' 127.0.0.1; # 本机
add_header 'Access-Control-Allow-Origin' www.test.com;
add_header 'Access-Control-Allow-Credentials' 'true' always; # 始终校验权限(别忘了这句)
./sbin/nginx -s reload 重启,测试通过。
location 添加if判断(未实测)
使用if也是同样的作用。
location @outputroute {
if ($remote_addr !~ ^(10.111.96.186|127.0.0.1)) {
rewrite ^/(.*) /output/index.html last;
}
}
元素
(1)Access-Control-Allow-Origin
该字段是必须的。它的值要么是请求时Origin字段的值,要么是一个*,表示接受任意域名的请求。
(2)Access-Control-Allow-Credentials
该字段可选。它的值是一个布尔值,表示是否允许发送Cookie。默认情况下,Cookie不包括在CORS请求之中。设为true,即表示服务器明确许可,Cookie可以包含在请求中,一起发给服务器。这个值也只能设为true,如果服务器不要浏览器发送Cookie,删除该字段即可。
(3)Access-Control-Expose-Headers
该字段可选。CORS请求时,XMLHttpRequest对象的getResponseHeader()方法只能拿到6个基本字段:Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma。如果想拿到其他字段,就必须在Access-Control-Expose-Headers里面指定。上面的例子指定,getResponseHeader(‘FooBar’)可以返回FooBar字段的值。
允许和拒绝
allow 192.168.1.101;
deny all;
也可以用子网掩码的形式:
allow 100.122.200.0/254;
access模块官网文档:
http://nginx.org/en/docs/http/ngx_http_access_module.html#allow