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;}