cors与Nginx

各个项目有用到公共头部,必然会涉及到模块跨域访问。

每个模块分别使用nginx 做负载均衡, nginx如果配置错误,会导致拦截跨域请求的资源。

1.nginx配置location,支持* 和 单个域名的限制,若现在有多个模块 即多个域,则应该使用下面的配置(不同版本的nginx配置会有差别)

set $cors "";
            if ($http_origin ~ "^(http://xxxx.biz.com|http://local.xxxx.biz.com:8080)$") {        //此为可能的多个模块的域名
               set $cors "true";
            }
        location / {


            proxy_pass   http://127.0.0.1:7001;
            if ($request_method = 'OPTIONS') {
               add_header 'Access-Control-Allow-Origin' "$http_origin";     // 此处取上面的值
               add_header 'Access-Control-Allow-Credentials' 'true';
               add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
               add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,X-Csrf-Token'; 
               # add_header 'Access-Control-Max-Age' 1728000;  
               add_header 'Content-Type' 'text/plain charset=UTF-8';
               add_header 'Content-Type' 'application/octet-stream';
               add_header 'Content-Length' 0;
              return 200;
            }
        }

2.相应的,在cros接口中 也需要对header头部参数做限制, * 和单个域名先不谈。主要说多个域名的情况:

可以根据refer 动态的设置:

private void parseAllowsUrl(HttpServletResponse response, HttpServletRequest request) {
try {
String referer = request.getHeader("Referer");
URL refer = new URL(referer);
String host = refer.getHost();
String protocol = refer.getProtocol();
Integer point = refer.getPort();
String refPath = protocol + "://" + host;
if(point!=-1){
refPath=refPath+":"+point;

String[] urls = allowsUrl.split(",");  // allowsUrl为允许访问的域,应用部署前就已知道,配置项。
for (String url : urls) {
if (StringUtils.equals(refPath, url)) {
response.addHeader("Access-Control-Allow-Origin", url);
response.setHeader("Access-Control-Allow-Credentials", "true"); // 动态设置
return;
}
}
} catch (Exception e) {
LOGGER.error("paese error", e);
}
}


3.客户端js需要设置跨域参数:

           xhrFields: {
            withCredentials: true
          },
          crossDomain: true,


至此可以实现, cros 支持多个域名的资源访问。

目前再说明一个问题:

公共头的css可能会使用@font-face重新定义字体,而这个也需要是跨域请求这些字体文件,在部分浏览器下(chrone,firefox),这些请求会经过CORS POLICY检验的。如果NGX在相应这些文件的时候没有带上Access-Control-Allow-Origin浏览会报错,并且这些资源会加载不成功。所以nginx配置location的限制还是很重要。


WebSocket跨域资源共享(Cross-Origin Resource Sharing, CORS)是在Web浏览器的同源策略限制下,允许服务器通过HTTP头部设置特定规则,使得来自不同源(协议、域名或端口)的网页可以互相通信的技术。当使用WebSocket非同源服务器通信时,如果没有正确的CORS配置,浏览器会阻止连接。 在Nginx配置中处理WebSocketCORS通常涉及以下几个步骤: 1. **开启WebSocket支持**: Nginx本身并不直接支持WebSocket,你需要安装第三方模块如`ngx_http_upstream_proxy_protocol_module`,并启用它。 ```nginx http { # 其他配置... proxy_protocol on; } ``` 2. **创建WebSocket专用的location块**: 使用`proxy_pass`指令,并指定WebSocket服务器地址。 ```nginx server { listen 80; # 或者443 location /ws { proxy_pass http://your-backend-server:8080; # 后端WebSocket服务地址 proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; add_header 'Access-Control-Allow-Origin' '*'; # 允许所有来源 add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; } } ``` 这里的`add_header`设置了CORS允许的头信息,`*`表示允许所有来源访问。 3. **处理OPTIONS预检请求**: 对于CORS,浏览器会在实际发送WebSocket请求前先发送一个`OPTIONS`请求检查是否允许跨域,Nginx需要正确响应这个请求。 ```nginx location = /ws { add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; if ($request_method = 'OPTIONS') { add_header 'Access-Control-Max-Age' 1728000; # 设置缓存时间 add_header 'Content-Length' 0; return 204; } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值