反向代理websocket

For NGINX to send the Upgrade request from the client to the backend server, the Upgrade and Connection headers must be set explicitly, as in this example:

  1. location /wsapp/ {
  2. proxy_pass http://wsbackend;
  3. proxy_http_version 1.1;
  4. proxy_set_header Upgrade $http_upgrade;
  5. proxy_set_header Connection "Upgrade";
  6. proxy_set_header Host $host;
  7. }


参考:NGINX as a WebSocket Proxy

Linux中配置

昨天在搭建测试环境时,一直无法转发请求,配置如下

  1. server {
  2. listen 80;
  3. server_name localhost;
  4. root /usr/share/nginx/html;
  5. location / {
  6. root /usr/share/nginx/html;
  7. try_files $uri $uri/ /index.html;
  8. }
  9. location /api {
  10. proxy_pass http://dingtalk_springboot:8080;
  11. }
  12. }

按照一篇博客修《nginx 反向代理用做内网域名转发》修改后成功

  1. server {
  2. listen 80;
  3. server_name localhost;
  4. root /usr/share/nginx/html;
  5. location / {
  6. root /usr/share/nginx/html;
  7. try_files $uri $uri/ /index.html;
  8. }
  9. location /api {
  10. proxy_set_header Host $host;
  11. proxy_set_header X-Real-IP $remote_addr;
  12. proxy_pass http://dingtalk_springboot:8080;
  13. }
  14. }

主要时proxy_set_header Host $host; 起作用

这一行的作用是把原http请求的Header中的Host字段也放到转发的请求里 而服务器是靠这个Host值来区分你请求的是哪个域名的资源的。

代理的后端服务器可以通过 Host 头得知用户访问的真正的域名, 如不设置, 则得到是代理服务(nginx)的 ip, 这样对于动态拼接的 url,后端服务器能在页面里返回正确的 url.

参考:

  1. nginx配置proxy_set_header Host $host的作用?

windows中配置

  1. 无法重新加载的问题