【问题标题】:Proxy redirecting websockets and http to the same (unix) socket代理将 websockets 和 http 重定向到同一个(unix)套接字
【发布时间】:2017-02-04 11:49:25
【问题描述】:

我做了一个小的 nginx 配置来将流量重定向到一个由 daphne 服务器(用于 django 的服务器)监听的 unix 套接字。

根据documentation

如果您对所有流量使用 Daphne,它会在 HTTP 和 WebSocket,因此无需将 WebSocket 放在单独的 端口或路径

所以我想将 websockets 和 Http 流量代理到同一个 unix 套接字。

  1. 有可能吗?

  2. 我该怎么办?

这是我迄今为止尝试过的:

upstream django_ws {
         server unix:///path/to/ws.sock;
}

server {
       listen 8082;
       server_name 127.0.0.1;
       charset utf-8;

       root /path/to/root;

       set $myroot $document_root;

       location / {
                proxy_pass http://django_ws;
                #proxy_http_version 1.1;
                #proxy_set_header Upgrade websocket;
                #proxy_set_header Connection upgrade;
       }
}
  • 如果我取消注释 location bloc 中的行,页面将显示为空白。

  • 如果我不这样做,页面会出现,但 websocket 似乎不起作用。

我该如何解决这个问题?

开发服务器一切正常。

【问题讨论】:

    标签: django nginx proxy websocket daphne


    【解决方案1】:

    我找到了解决办法:

    我像这样实例化我的 websocket:

    var socket = new WebSocket(ws_scheme + "://" + window.location.host
                               + "/ws" + window.location.pathname);
    

    所以我可以将发往 /ws 的请求和发往 / 的请求分开。

    所以我就这样做了:

    upstream django_ws {
             server unix:///path/to/ws.sock;
    }
    
    server {
           listen 8082;
           server_name 127.0.0.1;
           charset utf-8;
    
           root /path/to/root;
    
           set $myroot $document_root;
    
    
           location /ws {
                    proxy_pass http://django_ws;
                    proxy_http_version 1.1;
                    proxy_set_header Upgrade websocket;
                    proxy_set_header Connection upgrade;
           }
    
           location / {
                    proxy_pass http://django_ws;
           }
    }
    

    而且效果很好!

    【讨论】:

      猜你喜欢
      • 2021-09-06
      • 1970-01-01
      • 2016-07-31
      • 2014-07-18
      • 2011-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-30
      相关资源
      最近更新 更多