如何将自定义 header 从 NGINX 反向代理传递到服务器中的 SockJs websocket 连接?

How to pass custom header from NGINX Reverse Proxy to SockJs websocket connection in the server?

我正在使用 NGINX 作为反向代理。以下是 nginx.conf 文件中的设置。我想将自定义 header 从代理传递到 back-end HTTP 服务器。我确实在 HTTP 服务器中获得了自定义 header,但我没有在我的 sockJs 连接中获得它。

   proxy_set_header X-Real-IP $remote_addr;
   proxy_set_header X-RealIPRemote $realip_remote_addr;
   proxy_set_header X-RemoteAddr $remote_addr;
   proxy_set_header Host $host;
   proxy_set_header mycustomhdr customname;
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_pass http://192.168.1.1:18000;

   # WebSocket support
   proxy_http_version 1.1;
   proxy_set_header mycustomhdr customname;
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection "upgrade";

在代理连接到的 http 服务器中:

sockServer = sockJs.createServer(
... 
 sockServer.on('connection', function (conn) {
      console.log("conn.headers")
      console.log(conn.headers)

这是我得到的:

{ 'x-forwarded-for': '192.168.1.222',
        'x-real-ip': '192.168.1.222',
               host: 'example.com',
       'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36',
  'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8' }

我没有得到自定义 header mycustomhdr.

~

是的,你不会。您会注意到其他几个 headers 也不见了。并非所有 headers 都暴露。

来自the docs

headers (object) Hash containing various headers copied from last receiving request on that connection. Exposed headers include: origin, referer and x-forwarded-for (and friends). We explicitly do not grant access to cookie header, as using it may easily lead to security issues (for details read the section "Authorisation").