nginx 跨域问题解决

跨域的是一个老生常谈的问题,解决方法很多,但是实际使用中大家的方案可能或多或少都会有点问题
以下是自己的一个参考实践

一般玩法

使用add_header

 
location /  {
set $cors "";
if ($http_origin ~* (\.mydomain\.com|\.myseconddomain\.com)) {
   set $cors "true";
}
proxy_pass http://backend:10005/apathifyouwantso/;
if ($cors = "true") {
 add_header 'Access-Control-Allow-Origin' "$http_origin";
 add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT';
 add_header 'Access-Control-Allow-Credentials' 'true';
 add_header 'Access-Control-Allow-Headers' 'User-Agent,Keep-Alive,Content-Type';
}
}

或者直接使用openresty 的lua 模块

 access_by_lua_block {
                           ngx.header["Access-Control-Allow-Credentials"] = 'true'
                           ngx.header["Access-Control-Allow-Origin"] = '*'
                           ngx.header["Access-Control-Allow-Headers"] = 'Accept,Authorization,authorization,Cache-Control,Content-Type,appkey'
                           local httpmethod = ngx.req.get_method()
                           if httpmethod=="OPTIONS" then
                                  ngx.exit(ngx.HTTP_OK)
                           end           
                         --- 其他lua 处理逻辑
                         ......
 }

以上方案的问题

以上方案有一个问题就是加入我们已经后端的服务同时也添加cors 请求头,问题就很明显了,尤其是配置策略不同的时候,很容易造成重复响应请求头
发送(然后的问题就很明显了,cors 失效了。。。。)

比较优的方案

就是对于response 的header 进行重写,我们可以基于openresty 的header_filter_by_lua 或者使用headers-more-nginx-module
如果需要灵活控制的话,使用lua 模块比较好,如果是静态的可以直接使用headers-more-nginx-module
headers-more-nginx-module 参考

 
more_set_headers "Access-Control-Allow-Credentials: true";
more_set_headers "Access-Control-Allow-Origin: *";
more_set_headers "Access-Control-Allow-Headers: Accept,Authorization,authorization,Cache-Control,Content-Type,appkey";
access_by_lua_block {
      local httpmethod = ngx.req.get_method()
      if httpmethod=="OPTIONS" then
             ngx.exit(ngx.HTTP_OK)
      end
      --- 其他lua 处理逻辑
       ......
}

说明

基于nginx 解决跨域的方法很多,但是还是需要解决实际调整,同时需要利用好nginx 模块以及openresty 的能力

参考资料

https://github.com/openresty/headers-more-nginx-module
https://github.com/openresty/lua-nginx-module#header_filter_by_lua
http://nginx.org/en/docs/http/ngx_http_headers_module.html#add_header

posted on   荣锋亮  阅读(1554)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2021-04-15 cube.js dremio driver 类型转换bug修改
2021-04-15 xfs 磁盘扩容
2021-04-15 cube.js 动态编译问题
2020-04-15 几个不错的开源formbuilder
2019-04-15 nginx ngx_http_image_filter_module 简单试用
2015-04-15 TaffyDB:开源JavaScript数据库
2014-04-15 html 滚动固定显示js脚本

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示