Websocket链接如何配置nginx转发规则?

前端页面部署在localhost:8088端口上,后端websocket服务部署在localhost:8082端口上,下面介绍两种环境的转发规则。

前端接口:ws://localhost:8088/api/ws/runs/16?token=null

1、开发环境(vue3框架)

复制代码
const { defineConfig } = require('@vue/cli-service');

module.exports = defineConfig({
  publicPath: process.env.VUE_APP_BASE_URL,
  outputDir: `./dist/${process.env.VUE_APP_BASE_URL}`,
  transpileDependencies: true,
  productionSourceMap: false,
  css: {
    sourceMap: true,
  },
  chainWebpack: config => {
    config.devtool('eval-source-map')
  },
  chainWebpack: (config) => {
    config.plugin('define').tap((definitions) => {
      Object.assign(definitions[0], {
        __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: JSON.stringify(false),
        __VUE_OPTIONS_API__: JSON.stringify(true),
        __VUE_PROD_DEVTOOLS__: JSON.stringify(false),
      });
      return definitions;
    });
  },
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:8081',
        ws: true,
        changeOrigin: true
      },
    }
  }
});

2、生产环境

复制代码
        location ^~ /api/ws/ {
                proxy_pass http://127.0.0.1:8082;
                
                 proxy_http_version 1.1;
                 proxy_set_header Upgrade $http_upgrade;
                 proxy_set_header Connection "upgrade";
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                 proxy_set_header X-Forwarded-Proto $scheme;
                 
                proxy_read_timeout 3600s;
                proxy_send_timeout 3600s;
        }
相关推荐
遇见火星1 小时前
Nginx限流配置:防止接口被刷,服务器稳如泰山
运维·服务器·nginx
ai_coder_ai3 小时前
在自动化脚本中如何使用websocket?
websocket·autojs·自动化脚本·冰狐智能辅助·easyclick
凯瑟琳.奥古斯特4 小时前
NAT原理及作用详解
网络·网络协议
_Evan_Yao6 小时前
从 IP 路由到 Agent 路由:最长前缀匹配如何帮你分发任务?
java·网络·后端·网络协议·tcp/ip
数据法师16 小时前
开源情报收集工具GhostTrack深度测评:IP、手机号、用户名的合规信息查询方案
网络·网络协议·tcp/ip
想成为优秀工程师的爸爸18 小时前
第三十篇技术笔记:郭大侠学UDS - 人有生老三千疾,望闻问切良方医
网络·笔记·网络协议·tcp/ip·信息与通信
Jinkxs19 小时前
LoadBalancer- 主流负载均衡工具盘点:Nginx / Haproxy / Keepalived 基础介绍
运维·nginx·负载均衡
灰子学技术20 小时前
Envoy HTTP Connection Manager (HCM) 技术文档
网络·网络协议·http
ReaF_star21 小时前
【安全】SSL证书更新操作手册(Nginx+Cloudflare+acme.sh)
nginx·安全·ssl
云动课堂1 天前
【运维实战】Nginx 高性能Web服务 · 一键自动化部署方案 (适配银河麒麟 V10 / openEuler / CentOS 7/8)
运维·前端·nginx