Nginx代理Websocket

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

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容