nginx 如何代理websocket


前言

下面是配置nginx websocket 的代碼。

# HTTPS server
map $http_upgrade $connection_upgrade {

	default upgrade;
	'' close;
}

upstream websocket {
	server localhost:30000; #本地websocket反向代理地址
}
server {
	listen       443 ssl;
	server_name  www.51kanyisheng.com;

	ssl_certificate      D://ssl//wwwnginx//value.crt;
	ssl_certificate_key  D://ssl//wwwnginx//cert.key;

	ssl_session_cache    shared:SSL:1m;
	ssl_session_timeout  5m;

	ssl_protocols SSLv3 SSLv2 TLSv1 TLSv1.1 TLSv1.2;
	ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;

	location / {
		#root   html;
		#index  index.html index.htm;

		proxy_pass https://www.xxxx:10000;
	}
	# 監聽app
	location /websocket {  
		proxy_pass http://websocket;
		proxy_http_version 1.1;
		proxy_set_header Upgrade $http_upgrade;
		proxy_set_header Connection $connection_upgrade;
	   #proxy_set_header Host $host;
	}   

}

正文

為什么這么配置呢?

看一下如何建立websocket 配置:

首先瀏覽器會和我們溝通發布:

GET /webfin/websocket/ HTTP/1.1
Host: localhost
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: xqBt3ImNzJbYqRINxEFlkg==
Origin: http://localhost:8080
Sec-WebSocket-Version: 13

然后我們會一個:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: K7DJLdLooIwIG/MOpvWFB3y3FE8=

這其實是http協議,在websocket 連接建立之前我們需要去溝通切換協議。

$http_upgrade 客戶端請求中$http_upgrade 的值,來構造改變$connection_upgrade的值,即根據變量$http_upgrade的值創建新的變量$connection_upgrade

map 的詳解是:

https://blog.51cto.com/tchuairen/2175525?source=dra

在websocket 代理過程中,過一段時間會出現斷開的現象,這是因為nginx 代理默認了一段時間沒有響應就會斷開。

我們需要設置一個心跳包,合理的調整nginx 的斷開時間。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM