nginx+tomcat配置websocket反向代理

開發顯目中用到了websocket,架構是nginx+tomcat,所以需要在nginx配置反向代理websocket,於是我這個運維小白各種問度娘,在似懂非懂的情況下解決了當前需求。。。

知識拓展:

WebSocket 和HTTP协议不同,但是WebSocket中的握手和HTTP中的握手兼容,它使用HTTP中的Upgrade协议头将连接从HTTP升级到WebSocket。

nginx通过允许一个在客户端和后端服务器之间建立的隧道来支持WebSocket。为了NGINX发送来至于客户端Upgrade请求到后端服务器,Upgrade和Connection头部必须被设置明确。

配置:

(根據不同情況加入相應的配置)

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;  #把代理时http请求头的Upgrade 设置为原来http请求的请求头
proxy_set_header Connection "upgrade";  #代理的wss协议,所以http请求头的Connection设置为Upgrade
proxy_set_header X-real-ip $remote_addr;  #给代理设置原http请求的ip
proxy_set_header X-Forwarded-For $remote_addr

下面是我nginx.conf中location的配置:

(目前只有這個項目用到,所有只在location中配置的,也可以放在server{},只加了下面加粗的兩句)

location /epmp{
proxy_pass http://gw/epmp;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 600s;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
index index.html index.htm;
}

參考地址:https://www.jianshu.com/p/0244dfd135c9

注:本文主要用於個人學習與總結,如有錯誤期待各位大佬的指導!

原文地址:https://www.cnblogs.com/shiqing-zhang/p/12987280.html