Nginx代理Websocket

2020-07-06  本文已影响0人  hynial

Analysis

Websocket头部中端到端的头部信息需要被转发,因此需要在Nginx配置文件中对Websocket头部进行配置。

Actions

  1. 找到Websocket头部依赖的头部信息

    Websocket依赖的头部信息主要有两个:

    Connection 、 Upgrade

  2. 在Nginx配置文件中配置Websocket代理

    server {
     
      listen        80;
      listen        [::]:80
      server_name   your-website.com
      
      #this where socket io will be handling the request
      location /socket.io/ {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_pass "http://localhost:8000/socket.io/";
      }
      location / {
       proxy_pass "http://localhost:8000";
       proxy_http_version 1.1;
       proxy_set_header Upgrade $http_upgrade;
       proxy_set_header Connection 'upgrade';
       proxy_set_header Host $host;
       proxy_cache_bypass $http_upgrade;
      }
      error_page  404  /404.html;
       location = /40x.html{
       }
      error_page  500 502 503 504 /50x.html;
       location = /50x.html{
      } 
    }
    

    Especially Note:

    • 显示设置Http版本信息1.1
    • 增加需要转发的头部信息(connection and upgrade)
    • 【Don't Forget】请求中如果带有socket io,需要增加代理 /socket.io/
  3. Save the config file

Test & Taste

nginx -t
nginx -s reload

http://YourHost/

Bonus

顺便解决【Webrtc】Chrome浏览器无法直接(if your websocket use http)调用摄像头的问题?采用语句navigator.mediaDevices.getUserMedia调用摄像头的条件是要么localhost要么是https连接,所以如果不是在本地调用,就需要采用https安全协议,因此可以通过给Nginx添加CA证书(详见:简单搭建HTTPS or Install certbot(https))后通过代理转到http的Websocket端口。

Ref

how-to-proxy-websockets-with-nginx:

https://blog.usejournal.com/how-to-proxy-websockets-with-nginx-e333a5f0c0bb

上一篇 下一篇

猜你喜欢

热点阅读