欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > 前端如何使用Nginx代理dist网页,代理websocket,代理后端

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

2025/7/3 21:21:51 来源:https://blog.csdn.net/Franciz777/article/details/141201423  浏览:    关键词:前端如何使用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服务。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词