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 2022-04-15 21:27  荣锋亮  阅读(1504)  评论(0编辑  收藏  举报

导航