nginx反向代理websocket报403错误问题

nginx版本:1.10.3

nginx1.3以后才支持websocket

因项目需要服务端推送消息到web,使用H5的websocket来实现。

js代码:

  var websocket = null;
    var hostname = location.hostname;
    var port = location.port;
    var pathName=window.document.location.pathname;
    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://" + hostname + ":" + port + projectName + "/websocket.do");
    }
    else if ('MozWebSocket' in window) {
        websocket = new MozWebSocket("ws://" + hostname + ":" + port + projectName + "/websocket.do");
    }
    else {
        websocket = new SockJS(hostname + ":" + port + projectName + "/sockjs/websocket.do");
    }

    //已连接
    websocket.onopen = function (event) {
        console.log("连接建立");
    };
//省略...

服务端使用springMVC的webSocket,配置.do请求

//前台可以使用websocket环境
        webSocketHandlerRegistry.addHandler(goodsWebsocketHandler(),"/websocket.do").addInterceptors(new HandshakInterceptor());

        //前台不可以使用websocket环境
        webSocketHandlerRegistry.addHandler(goodsWebsocketHandler(),"/sockjs/websocket.do").addInterceptors(new HandshakInterceptor()).withSockJS();

使用nginx代理端口请求时直接报403,查资料发现nginx必须配置协议头才能受理webSocket。

配置如下:

location /xhx/ {
			proxy_pass $http_host;
			proxy_http_version 1.1;  
			proxy_set_header Upgrade $http_upgrade;  
			proxy_set_header Connection "upgrade"; 
        }

结果还是报403,度娘后发现是Origin必须一致,对.do请求的代码做下修改,忽略Origin,加上下面代码:

.setAllowedOrigins("*")
//前台可以使用websocket环境
        webSocketHandlerRegistry.addHandler(goodsWebsocketHandler(),"/websocket.do").addInterceptors(new HandshakInterceptor()).setAllowedOrigins("*");

        //前台不可以使用websocket环境
        webSocketHandlerRegistry.addHandler(goodsWebsocketHandler(),"/sockjs/websocket.do").addInterceptors(new HandshakInterceptor()).withSockJS();
再试下,OK,问题解决!


文章来源: nginx反向代理websocket报403错误问题

人吐槽 人点赞

猜你喜欢

发表评论

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:nginx反向代理websocket报403错误问题