nginx跨域配置

nginx跨域配置:

在前后端分离项目中经常会遇到跨域问题。在开发阶段前端可以采用node做代理解决,
但是一旦项目上线,node无法做代理。这时就必须由后端解决跨域。

问题描述:

后端代码可能已经写好并测试完成,也不想做太大的改动,且后端一般都是nginx后面接网关,网关可能为zuul或者gateway,zuul的跨域还比较好解决 加一个跨域过滤器 , 但是gateway提供的跨域过滤器有问题,不是很理想。

原因分析:

由于前端是先请求到nginx再请求到后面的微服务。在不想改动后端代码的前提下,
可以直接配置nginx,让nginx实现跨域,这样后端服务不需要任何改动。

解决方案:

nginx配置跨域,只需要在响应头中加入如下4个请求头即可完美解决

// 这个为请求头中的 origin
add_header 'Access-Control-Allow-Origin' '$http_origin' ;
add_header 'Access-Control-Allow-Credentials' 'true' ;
add_header 'Access-Control-Allow-Methods' 'PUT,POST,GET,DELETE,OPTIONS' ;
add_header 'Access-Control-Allow-Headers' 'Content-Type,Content-Length,Authorization,Accept,X-Requested-With' ;

nginx 配置跨域,可以为全局配置和单个代理配置(两者不能同时配置)

  1. 全局配置,在nginx.conf文件中的 http 节点加入跨域信息
http {
    # 跨域配置
    add_header 'Access-Control-Allow-Origin' '$http_origin' ;
    add_header 'Access-Control-Allow-Credentials' 'true' ;
    add_header 'Access-Control-Allow-Methods' 'PUT,POST,GET,DELETE,OPTIONS' ;
    add_header 'Access-Control-Allow-Headers' 'Content-Type,Content-Length,Authorization,Accept,X-Requested-With' ;
  1. 局部配置(单个代理配置跨域), 在路径匹配符中加入跨域信息

server {
        listen       8081;
        server_name  nexus;

        charset utf-8;

        # 日志文件位置及其输出格式
        access_log  logs/nexus/access.log  json;
        error_log logs/nexus/error.log crit;

        location / 
        # 这里配置单个代理跨域,跨域配置
         add_header 'Access-Control-Allow-Origin' '$http_origin' ;
         add_header 'Access-Control-Allow-Credentials' 'true' ;
         add_header 'Access-Control-Allow-Methods' 'PUT,POST,GET,DELETE,OPTIONS' ;
         add_header 'Access-Control-Allow-Headers' 'Content-Type,Content-Length,Authorization,Accept,X-Requested-With' ;

            #配置代理
            proxy_pass http://nexusServers;
            proxy_redirect   off;
            proxy_set_header Host $host:$server_port;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
  }
  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值