nginx配置反向代理地址
文章目录
-
- 1. nginx 反向代理 api
- 2. nginx 反向代理WebSocket
- 3. nginx 反向代理服务器上的静态资源
- 4. vite.config.dev.ts
- 5. websocket.ts
当我们把地址都写进 nginx 进行代理时,一般是后端地址、websocket地址、静态资源加载地址
worker_processes auto;events {worker_connections 1024;
}http {include mime.types;default_type application/octet-stream;#log_format main '$remote_addr - $remote_user [$time_local] "$request" '# '$status $body_bytes_sent "$http_referer" '# '"$http_user_agent" "$http_x_forwarded_for"';#access_log logs/access.log main;sendfile on;#tcp_nopush on;#keepalive_timeout 0;keepalive_timeout 65;# HTTPS serverserver {listen 8888;server_name localhost;#charset koi8-r;#access_log logs/host.access.log main;root ./html/dist/;index index.html index.htm;location / {# 截取404 的 url,传给 @routertry_files $uri $uri/ @router;}location /api {proxy_pass http://192.168.1.33:8001;proxy_redirect default;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_read_timeout 3600s;}location /wsURL/ {rewrite ^/wsURL/(.*)$" /$1 break; proxy_http_version 1.1;proxy_pass http://192.168.1.33:8001/wsbackend/dashboard;proxy_redirect default;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection $connection_upgrade;}location /assestMap {proxy_pass http://192.168.1.33:8002;proxy_redirect default;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}location @router {# 接到截取的 uri 并按一定规则重写 uri和vue路由跳转rewrite…….*$ /index.html last}}
}
1. nginx 反向代理 api
location /api {proxy_pass http://192.168.1.33:8001;proxy_redirect default;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_read_timeout 3600s;}
2. nginx 反向代理WebSocket
参考地址:http://nginx.org/en/docs/http/websocket.html
server {listen 20038;location /{proxy_http_version 1.1;proxy_pass http://wsbackend;proxy_redirect off;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_read_timeout 3600s;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection $connection_upgrade;}
}
- location 表示的是监听的服务器的配置
- listen 20038 表示 nginx 监听的端口
- locations / 表示监听的路径(/表示所有路径,通用匹配,相当于default)
- proxt_http_version 1.1 表示反向代理发送的HTTP协议的版本是1.1,HTTP1.1支持长连接
- proxy_pass http://wsbackend; 表示反向代理的uri,这里可以使用负载均衡变量
- proxy_redirect off; 表示不要替换路径,其实这里如果是/则有没有都没关系,因为default也是将路径替换到proxy_pass的后边
- proxy_set_header Host $host; 表示传递时请求头不变, $host是nginx内置变量,表示的是当前的请求头,proxy_set_header表示设置请求头
- proxy_set_header X-Real-IP $remote_addr; 表示传递时来源的ip还是现在的客户端的ip
- proxy_read_timeout 3600s; 表的两次请求之间的间隔超过 3600s 后才关闭这个连接,默认的60s,自动关闭的元凶
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 表示X-Forwarded-For头不发生改变
- proxy_set_header Upgrade $http_upgrade; 表示设置Upgrade不变
- proxy_set_header Connection $connection_upgrade; 表示如果 $http_upgrade为upgrade,则请求为upgrade(websocket),如果不是,就关闭连接
- 若是实际使用的websocket地址后面还有路径,比如实际地址是这样的,访问地址是 http://www.a.com,实际会转发给ws://127.0.0.1:8094/ws
server {listen 80;server_name api.leyou.com;proxy_set_header X-Forwarded-Host $host;proxy_set_header X-Forwarded-Server $host;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;# 上传路径的映射location /api/upload { proxy_pass http://127.0.0.1:8082;proxy_connect_timeout 600;proxy_read_timeout 600;rewrite "^/api/(.*)$" /$1 break; }location / {proxy_pass http://127.0.0.1:10010;proxy_connect_timeout 600;proxy_read_timeout 600;}}
- 首先,我们映射路径是/api/upload,而下面一个映射路径是 / ,根据最长路径匹配原则,/api/upload优先级更高。也就是说,凡是以/api/upload开头的路径,都会被第一个配置处理
- proxy_pass:反向代理,这次我们代理到8082端口,也就是upload-service服务
rewrite “^/api/(.*)$” /$1 break
,路径重写:- “^/api/(.*)$”:匹配路径的正则表达式,用了分组语法,把/api/以后的所有部分当做1组
- /$1:重写的目标路径,这里用$1引用前面正则表达式匹配到的分组(组编号从1开始),即/api/后面的所有。这样新的路径就是除去/api/以外的所有,就达到了去除/api前缀的目的
- break:指令,常用的有2个,分别是:last、break
- last:重写路径结束后,将得到的路径重新进行一次路径匹配
- break:重写路径结束后,不再重新匹配路径。 我们这里不能选择last,否则以新的路径/upload/image来匹配,就不会被正确的匹配到8082端口了
- 修改完成,输入nginx -s reload命令重新加载配置。然后再次上传试试。
3. nginx 反向代理服务器上的静态资源
location /assestMap {proxy_pass http://192.168.1.33:8002;proxy_redirect default;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}
4. vite.config.dev.ts
import { mergeConfig } from 'vite';
// import eslint from 'vite-plugin-eslint';
import baseConfig from './vite.config.base';export default mergeConfig({mode: 'development',server: {open: true,port: 9001, // 端口号fs: {strict: true,},// 地址代理proxy: {'/api': {target: 'http://192.168.1.33:8001/', //请求的地址changeOrigin: false,rewrite: (path) => path.replace(/^\\/api/, ''),},'/wsURL': {target: 'ws://192.168.1.33:8001/wsbackend/dashboard', //请求的地址changeOrigin: false,ws: true,secure: false,rewrite: (path) => path.replace(/^\\/wsURL/, ''),},'/assestMap': {target: 'http://192.168.1.10:6601/', //请求的地址changeOrigin: false,rewrite: (path) => path.replace(/^\\/assestMap/, ''),},},},plugins: [// eslint({// cache: false,// include: ['src/**/*.ts', 'src/**/*.tsx', 'src/**/*.vue'],// exclude: ['node_modules'],// }),],},baseConfig
);
5. websocket.ts
/*** websocket*/
// const wsUrl = 'ws://xxxxxxxxxxxxx'; // websocket 默认连接地址
let websocket: any; // 用于存储实例化后websocket
let isConnect = false; // 连接标识 避免重复连接
let rec: any; // 断线重连后,延迟5秒重新创建WebSocket连接 rec用来存储延迟请求的代码// 创建websocket 必要时传参 并将url改为在函数内部编写
function creatWebSocket() {console.log('websocket==================');// 判断当前浏览器是否支持WebSocketif ('WebSocket' in window) {console.log('当前浏览器 windows');} else if ('MozWebSocket' in window) {console.log('当前浏览器 windows');} else {console.log('当前浏览器 Not support websocket');}try {initWebSocket(); // 初始化websocket连接} catch (e) {console.log('尝试创建连接失败');reConnect(); // 如果无法连接上 webSocket 那么重新连接!可能会因为服务器重新部署,或者短暂断网等导致无法创建连接}
}// 初始化websocket
function initWebSocket() {websocket = new WebSocket(`ws://${location.host}/wsURL/`);console.log('websocket:', websocket);websocket.onopen = function (e: any) {websocketOpen(e);};// 接收websocket.onmessage = function (e: any) {websocketonmessage(e);};// 连接发生错误websocket.onerror = function () {console.log('WebSocket连接发生错误');isConnect = false; // 连接断开修改标识reConnect(); // 连接错误 需要重连};websocket.onclose = function (e: any) {websocketclose(e);};
}// 定义重连函数
let reConnect = () => {console.log('尝试重新连接');if (isConnect) return; // 如果已经连上就不在重连了rec && clearTimeout(rec);rec = setTimeout(function () {// 延迟5秒重连 避免过多次过频繁请求重连creatWebSocket();}, 5000);
};// 创建连接
function websocketOpen(e: any) {console.log('连接成功');
}
// 数据接收
function websocketonmessage(e: any) {console.log('数据接收', e.data);// let data = JSON.parse(decodeUnicode(e.data))
}
// 关闭
function websocketclose(e: any) {console.log(e);isConnect = false; // 断开后修改标识console.log(`connection closed (${e.code})`);
}// 数据发送
function websocketsend(data: any) {console.log('发送的数据', data, JSON.stringify(data));websocket.send(JSON.stringify(data));
}// 实际调用的方法==============// 发送
function sendWebSocket(data: any) {if (websocket.readyState === websocket.OPEN) {// 开启状态websocketsend(data);} else {// 若 未开启 / 正在开启 状态 ,则等待1s后重新调用setTimeout(() => {sendWebSocket(data);}, 1000);}
}// 关闭
const closeWebSocket = () => {websocket.close();
};export { sendWebSocket, creatWebSocket, closeWebSocket };