nginx跨域访问配置(web反向代理跨域访问配置)
出于安全的原因,浏览器限制从脚本内发起跨域的http
请求,除非响应报文中包含了允许浏览器解析报文的cors
响应头
也就是说,响应报文的头中要有以下几个响应头
nginx
要使用add_header
添加这几个响应头
1.前后端分离的工程
一般情况下是使用ajax
访问后端接口
ajax
的请求头为x-requested-with
因此服务端要允许x-requested-with
的请求头
add_header 'access-control-allow-headers' 'x-requested-with';
2.服务端要配置哪些域
是可以跨域访问到本服务器资源的
add_header 'access-control-allow-origin' '*';
注意:
- 如果使用了
add_header 'access-control-allow-credentials' 'true'
- 那么不能使用通配符
add_header 'access-control-allow-origin' 'www.baidu.com'; add_header 'access-control-allow-credentials' 'true';
3.服务器端要指定http请求的方法
add_header 'access-control-allow-methods' 'get,post,options'
案例
add_header 'access-control-allow-origin' '*'; add_header 'access-control-allow-headers' 'x-requested-with'; add_header 'access-control-allow-methods' 'get,post,options' # 由于跨域请求,浏览器会先发送一个options的预检请求,我们可以缓存第一次的预检请求的失效时间 if ($request_method = 'options') { add_header 'access-control-max-age' 2592000; add_header 'content-type' 'text/plain; charset=utf-8'; add_header 'content-length' 0; return 204; }
http
请求头详解
对于跨域的配置,不是只有nginx
可以配置,在spring
中也提供了跨域访问的配置
详见corsfilter
、corsconfiguration
、urlbasedcorsconfigurationsource
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论