当前位置: 首页 > news >正文

前端如何使用Nginx代理dist网页,代理websocket,代理后端

本文将指导您如何配置Nginx以代理前后端分离的项目,并特别说明了对WebSocket的代理设置。通过本教程,您将能够实现一次性配置,进而使项目能够在任意局域网服务器上部署,并可通过IP地址或域名访问服务。

笔者建议 先速览本文了解大致内容后再复制对应的代码。本文环境基于Windows VUE3 typescript 理论通用于linux

前提条件

  • 已安装Nginx

  • 前后端项目代码部署在服务器上

Nginx配置步骤

基础代理配置

编辑Nginx配置文件,通常位于/etc/nginx/nginx.conf/etc/nginx/conf.d/目录下的某个.conf文件。例如:

server {listen       80; # 监听端口server_name  localhost; # 服务器名称 局域网内一般就是localhost
​location / {proxy_pass http://前端项目地址; # 前端项目代理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 /api/ {proxy_pass http://后端项目地址; # 后端接口代理proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}
}

为了自动化区分生产环境和开发环境,我们需要使用到“.env”

如图通过.env.development      .env.production  然后修改 package.json即可自动区分环境。然后再请求代码中这样写

export const BASE_URL = import.meta.env.VITE_APP_BASE_API

以下为笔者实例配置


#user  nobody;
worker_processes  2;#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;pid        logs/nginx.pid;events {worker_connections  2048;
}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;#gzip  on;server {listen 8119;server_name localhost;# 指定根目录为 dist 文件夹root ./dist;index index.html;location / {try_files $uri $uri/ /index.html;}# 将以/api开始的请求代理到本机的8112端口的后端服务,并且去掉URL中的/apilocation /api/ {proxy_pass http://localhost:8112/; # 注意这里的尾部斜线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;# 其他可能需要的代理设置...}# 添加通用 WebSocket 代理location /ws/ {proxy_pass http://localhost:8112;proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "Upgrade";proxy_set_header Host $host;proxy_read_timeout 60s;proxy_send_timeout 60s;}}server {listen       80;server_name  localhost;#charset koi8-r;#access_log  logs/host.access.log  main;location / {root   html;index  index.html index.htm;}#error_page  404              /404.html;# redirect server error pages to the static page /50x.html#error_page   500 502 503 504  /50x.html;location = /50x.html {root   html;}# proxy the PHP scripts to Apache listening on 127.0.0.1:80##location ~ \.php$ {#    proxy_pass   http://127.0.0.1;#}# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000##location ~ \.php$ {#    root           html;#    fastcgi_pass   127.0.0.1:9000;#    fastcgi_index  index.php;#    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;#    include        fastcgi_params;#}# deny access to .htaccess files, if Apache's document root# concurs with nginx's one##location ~ /\.ht {#    deny  all;#}}# another virtual host using mix of IP-, name-, and port-based configuration##server {#    listen       8000;#    listen       somename:8080;#    server_name  somename  alias  another.alias;#    location / {#        root   html;#        index  index.html index.htm;#    }#}# HTTPS server##server {#    listen       443 ssl;#    server_name  localhost;#    ssl_certificate      cert.pem;#    ssl_certificate_key  cert.key;#    ssl_session_cache    shared:SSL:1m;#    ssl_session_timeout  5m;#    ssl_ciphers  HIGH:!aNULL:!MD5;#    ssl_prefer_server_ciphers  on;#    location / {#        root   html;#        index  index.html index.htm;#    }#}}

其中前端的dist目录笔者使用的是相对路径,也就意味着/conf/nginx.conf中./ 相对的根目录是conf的同级目录。这也是实现通用化部署的关键。这样配置在其他地方解压后仍然可以生效。

而后端则是全部以 /api 作为默认的请求的url,然后通过nginx反向代理到真实的后端。

例如请求的是 /api/login 到服务器 则被代理后为 http://localhost:8112/login  即指向了服务器自身。

WebSocket代理配置

在配置文件中增加针对WebSocket的代理设定。这段代码除了服务地址和指定的代理的路径“/ws/”其余部分是固定配置。

    # 添加通用 WebSocket 代理location /ws/ {proxy_pass http://localhost:8112;proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "Upgrade";proxy_set_header Host $host;proxy_read_timeout 60s;proxy_send_timeout 60s;}

而websocket则需要再代码中这样写

 socket = new WebSocket(`ws://${window.location.host}/ws/upgrade_log`);

此行代码用于创建一个新的WebSocket连接。具体解释如下:

  • ws://${window.location.host}/ws/upgrade_log:这是一个模板字符串,用来定义WebSocket服务器的URL。

    • ws://:是WebSocket协议的前缀,表示这是一个WebSocket连接。在安全环境中(例如使用HTTPS时),会使用wss://作为前缀。

    • ${window.location.host}:这部分代码使用了JavaScript的模板字符串语法来嵌入一个表达式。window.location.host获取当前浏览器窗口中显示的文档的主机名(即域名或IP地址加端口号)。这意味着WebSocket连接到当前页面所在的域名或IP地址上。

    • /ws/upgrade_log:这是WebSocket服务在服务器上的具体路径。在Nginx配置中,我们可能设置了一个location块来监听/ws/路径,并将其代理到实际运行WebSocket服务的后端服务器。

所以,整行代码的作用是,在客户端创建一个WebSocket连接,连接到与当前网页相同host的服务器上,特定的/ws/upgrade_log路径。当这个WebSocket连接建立后,就可以用于双向通信,客户端和服务器可以互相发送消息。

然后通过Nginx的代理实现任何通过ip访问前端网页时都能连接到服务器的websocket服务。

http://www.lryc.cn/news/424183.html

相关文章:

  • Cannot connect to the Docker daemon at unix:///var/run/docker.sock. 问题解决
  • 零基础学习Redis(2) -- Redis安装与配置
  • UniApp第一天
  • TLE4966-3G带方向检测功能的高灵敏度汽车霍尔开关
  • Github 2024-08-14 C开源项目日报Top10
  • 飞桨Paddle API index_add 详解
  • 后端代码练习1——加法计算器
  • 观察者模式和MQ是什么关系
  • JDK动态代理和CGLIB动态代理案例分析
  • 【数据结构-前缀哈希】力扣1124. 表现良好的最长时间段
  • 电商平台产品ID|CDN与预渲染|前端边缘计算
  • LATTICE进阶篇DDR2--(4)DDR2 IP核总结
  • windows下php安装kafka
  • 【wiki知识库】09.欢迎页面展示(浏览量统计)SpringBoot部分
  • 数据分析与应用:微信-情人节红包流向探索分析
  • SQL,获取 ID 的历史状态
  • 阅文集团:摇不动的IP摇钱树
  • ETL数据集成丨将SQL Server数据同步至Oracle的具体实现
  • 20240814软考架构-------软考51-55答案解析
  • JavaEE 的入门
  • vue3+ts 前端word文档下载文件时不预览直接下载方法(支持 doc / excel / ppt / pdf 等)
  • Java 空值与null 形参与实参学习
  • 【QT常用技术讲解】QTableView添加QCheckBox、QPushButton
  • linux监控命令
  • SpringBoot入门笔记
  • python 华为od 单词接龙
  • Vue+Echart实现地图省市区三级下钻
  • Apache Tomcat 信息泄露漏洞排查处理CVE-2024-21733)
  • 51单片机-LED实验
  • 无人机开启农林植保新篇章