nginx支持webSocket ws请求(解决:WebSocket connection to 'ws://...' failed: Error during WebSocket handshake: Unexpected response code: 200)
服务端webSocket的java配置文件:
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
//允许使用socketJs方式访问,访问点为webSocket,允许跨域
//在网页上我们就可以通过这个链接
//ws://127.0.0.1:8585/webSocket来和服务器的WebSocket连接
registry.addEndpoint("/webSocket").setAllowedOrigins("*");
}
本地开发时,测试webSocket链接时,直接用的请求为:ws://127.0.0.1:8585/webSocket,其中webSocket为服务端的自己配置的访问点,访问成功,如下图:
当部署到使用nginx转发的生产环境时,nginx配置:
location /api/ {
rewrite ^/api/(.*)$ /$1 break;
proxy_pass http://127.0.0.1:8585;
...
}
当前访问的请求为:ws://域名:2222/api/webSocket,访问失败,如下图:
异常为:WebSocket connection to 'ws://...' failed: Error during WebSocket handshake: Unexpected response code: 200
此时,需要nginx配置支持websocket协议ws://,正确的nginx配置为:
location /api/ {
rewrite ^/api/(.*)$ /$1 break;
proxy_pass http://127.0.0.1:8585;
...
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
访问成功: