前端必知:Nginx代理实战全指南

一、先搞懂:前端视角的 Nginx 代理核心概念

1. 什么是 Nginx 代理?

Nginx 是一款高性能的 HTTP 服务器 / 反向代理服务器,对前端来说,「代理」就是:

  • 前端请求 → 先发给 Nginx 服务器 → Nginx 代替前端请求后端接口 / 获取资源 → Nginx 将结果返回给前端。
  • 核心价值:突破浏览器「同源策略」(跨域)、统一接口域名、优化资源加载(缓存 / 压缩)。
2. 代理的核心类型(前端只关注这 2 种)
代理类型核心作用前端使用场景
反向代理(常用)Nginx 代理前端请求到后端服务器(隐藏后端地址)解决跨域、接口转发、部署多环境
正向代理Nginx 代理前端访问外部网络(如翻墙)开发环境访问外网接口(极少用)

对前端来说,99% 的场景都是「反向代理」,下文所有内容均围绕反向代理展开。

二、前端日常项目中 Nginx 代理的核心使用场景

场景 1:解决开发 / 生产环境的跨域问题(最核心)

浏览器的「同源策略」要求前端页面和接口的「协议、域名、端口」必须一致,否则跨域。Nginx 代理能让前端请求先到 Nginx(同源),再由 Nginx 转发到后端(Nginx 无跨域限制)。

(1)开发环境:本地 Nginx 代理(替代 devServer 代理)
  • 适用场景:后端接口未配置 CORS,或本地 devServer 代理满足不了复杂需求(如多域名转发)。

前端代码中请求写法(无需写完整后端地址,直接请求同源的 /api):

// 前端请求:http://localhost:8080/api/user → Nginx 转发到 http://192.168.1.100:8081/user axios.get('/api/user').then(res => console.log(res)); 

配置示例(nginx.conf):nginx

# 配置 Nginx 监听本地端口(和前端页面同源) server { listen 8080; # 前端页面运行在 http://localhost:8080 server_name localhost; # 代理后端接口:前端请求 /api → 转发到后端真实地址 location /api/ { # 后端接口真实地址 proxy_pass http://192.168.1.100:8081/; # 关键配置:传递请求头(解决跨域+后端识别来源) 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; } # 代理前端静态资源(本地打包后的dist目录) location / { root /Users/xxx/project/dist; # 前端dist目录绝对路径 index index.html index.htm; try_files $uri $uri/ /index.html; # 解决Vue/React路由刷新404 } } 
(2)生产环境:服务器 Nginx 代理(部署必用)
  • 适用场景:前端打包后部署到服务器,接口请求通过 Nginx 转发,避免跨域 + 隐藏后端真实地址。

核心配置(生产环境优化版):nginx

server { listen 80; server_name www.xxx.com; # 前端域名 # 静态资源缓存(优化加载速度) location ~* \.(js|css|png|jpg|gif|svg)$ { root /usr/share/nginx/html; # 前端dist目录 expires 7d; # 静态资源缓存7天 gzip on; # 开启gzip压缩 } # 接口代理:前端请求 /api → 转发到后端服务器集群 location /api/ { proxy_pass http://backend_server/; # 后端集群地址(可配置多个) proxy_connect_timeout 60s; # 连接超时 proxy_read_timeout 60s; # 读取超时 # 跨域头(生产环境若前端和Nginx同源,可省略) add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods 'GET,POST,PUT,DELETE'; } # 前端路由兼容(Vue/React History模式) location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri $uri/ /index.html; # 刷新页面不404 } } 
场景 2:多环境接口转发(开发 / 测试 / 生产)

前端开发中常需切换接口环境(开发 / 测试 / 生产),Nginx 可通过不同 location 配置转发到不同后端:

server { listen 8080; server_name localhost; # 开发环境接口 location /api/dev/ { proxy_pass http://dev.xxx.com/; } # 测试环境接口 location /api/test/ { proxy_pass http://test.xxx.com/; } # 生产环境接口 location /api/prod/ { proxy_pass http://prod.xxx.com/; } } 

前端只需修改请求路径(如 /api/dev/user → /api/test/user),即可切换环境,无需改代码。

场景 3:静态资源优化(部署阶段)

Nginx 可代理前端静态资源(JS/CSS/ 图片),并配置缓存、压缩、防盗链,提升页面加载速度:

server { listen 80; server_name www.xxx.com; # 静态资源配置 location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ { root /usr/share/nginx/html; expires 30d; # 缓存30天 gzip on; # 开启gzip压缩(减小文件体积) gzip_types text/css application/javascript image/png; # 压缩类型 # 防盗链(只允许自己域名访问资源) valid_referers www.xxx.com; if ($invalid_referer) { return 403; } } # 前端页面 location / { root /usr/share/nginx/html; index index.html; try_files $uri $uri/ /index.html; } } 
场景 4:本地开发代理(替代 Vue CLI/ Vite 内置代理)

Vue CLI 的 devServer.proxy、Vite 的 server.proxy 本质是「Node 代理」,但复杂场景(如多域名、自定义请求头)不如 Nginx 灵活。

  • 举例:Vite 项目改用 Nginx 代理:
    1. 启动 Vite 项目:npm run dev(运行在 http://localhost:5173);
    2. 前端请求 /api/user → Nginx 转发到后端,解决跨域。

配置 Nginx 监听 5173,转发接口:

server { listen 5173; server_name localhost; # 代理接口到后端 location /api/ { proxy_pass http://192.168.1.100:8081/; } # 代理 Vite 开发服务器(前端页面) location / { proxy_pass http://localhost:5173/; proxy_set_header Host $host; } } 

三、前端使用 Nginx 代理的核心步骤(实战流程)

步骤 1:安装 Nginx(本地 / 服务器)
  • 本地(Mac):brew install nginx
  • 本地(Windows):官网下载压缩包,解压后运行 nginx.exe
  • 服务器(Linux):yum install nginx(CentOS)/ apt install nginx(Ubuntu)。
步骤 2:修改 Nginx 配置文件
  • 本地配置文件路径:
    • Mac:/usr/local/etc/nginx/nginx.conf
    • Windows:nginx-xxx/conf/nginx.conf
  • 服务器配置文件路径:/etc/nginx/nginx.conf 或 /etc/nginx/conf.d/default.conf
  • 核心:修改 server 块,添加代理规则(参考上面的场景配置)。
步骤 3:启动 / 重启 Nginx
# 启动 Nginx nginx # 重启 Nginx(修改配置后) nginx -s reload # 停止 Nginx nginx -s stop # 检查配置是否正确 nginx -t 
步骤 4:前端代码适配
  • 接口请求路径改为「相对路径」(如 /api/user),而非完整后端地址(如 http://192.168.1.100:8081/user);
  • 无需配置跨域相关代码(如 withCredentials),由 Nginx 处理。

四、前端视角的 Nginx 代理核心总结

1. 核心作用(前端关心的 3 件事)
  • 解决跨域:Nginx 作为中间层,让前端请求和 Nginx 同源,Nginx 再转发到后端(绕过浏览器跨域限制);
  • 接口转发:统一接口域名,切换环境只需改 Nginx 配置,无需改前端代码;
  • 优化部署:缓存静态资源、压缩文件、兼容前端路由(History 模式)。
2. 日常使用高频场景
场景核心配置关键词
跨域接口代理proxy_pass + 跨域头
前端路由兼容try_files $uri $uri/ /index.html
静态资源缓存expires + gzip
多环境接口转发不同 location 配置
3. 关键注意点
  • 配置 proxy_pass 时,末尾的 / 很关键:
    • proxy_pass http://backend/;:前端请求 /api/user → 转发到 http://backend/user
    • proxy_pass http://backend;:前端请求 /api/user → 转发到 http://backend/api/user
  • 本地开发优先用 Vue CLI/Vite 内置代理(更轻便),复杂场景再用 Nginx;
  • 生产环境部署时,Nginx 配置需加 try_files 解决前端路由刷新 404 问题。

简单记:对前端来说,Nginx 代理就是「解决跨域的中间服务器」+「部署优化的工具」,核心配置就围绕 proxy_pass(转发)、try_files(路由)、expires/gzip(资源)这几个关键点。

// 后端代码 const Koa = require('koa') const Router = require('koa-router') const app = new Koa() const router = new Router() router.get('/api/login', async ctx=>{ ctx.body = 'login success' }) app.use(router.routes()) app.listen(3000,()=> console.log('server running at port 3000...') })
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=1920,maximum-scale=1.3,user-scalable=no"> <title>前端页面</title> </head> <body> <h1>前端页面,运行在800端口</h1> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script> axios.get('/api/login').then(res => { console.log('data',res.data) }) </script> </body> </html> 
# nginx反向代理 请求--->8080 请求路径为/,代理到8000端口(前端) 请求路径为/api,代理到3000端口(后端) localhost:8080/index.html,代理到localhost:8000/index.html localhost:8080/api/login,代理到localhost:3000/api/login 
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 8080; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { proxy_pass http://localhost:8000; } location /api { proxy_pass http://localhost:3000; } #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; #} }

Read more

Docker:Docker部署Neo4j图数据库

Docker:Docker部署Neo4j图数据库

Docker:Docker部署Neo4j图数据库 前言 Neo4j是一个高性能的,基于java开发的,NOSQL图形数据库,它将结构化数据存储在网络上而不是表中;它是一个嵌入式的、基于磁盘的、具备完全的事务特性的Java持久化引擎。 Neo4j分为企业版和社区版,企业版可以创建多个数据库,链接多个数据库,但是收费……;社区版只能链接一个数据库,所以社区版不支持创建数据库命令。 Neo4j部署后默认创建名字为 neo4j 的数据库,可以直接链接这个数据库 拉取镜像 # 下载镜像 docker pull neo4j:5.26.2 也可以不指定版本 构建容器 # 创建neo4j容器 docker run -it -d -p 7474:7474 -p 7687:7687 \ -v /home/neo4j/data:/data \ -v /home/neo4j/logs:

AI × 低代码 × 工程化:Oinone Pamirs 的下一代产品化引擎实践

AI × 低代码 × 工程化:Oinone Pamirs 的下一代产品化引擎实践 一、传统企业软件交付的「不可能三角」困境 在传统企业软件开发领域,长期存在一个被称为「不可能三角」的困境:交付速度、产品质量与成本控制三者难以兼得。追求快速上线往往牺牲稳定性;强调高质量则拖慢节奏;控制成本又可能导致功能缩水或技术债堆积。尤其在定制化项目泛滥的行业(如政务、金融、制造),软件公司常年陷于「接单—开发—维护—再接单」的恶性循环中,难以形成可复用的产品资产。 1.1 项目制开发的致命缺陷 当前,大量中小型软件公司仍采用「项目制」开发模式:每个客户提出差异化需求,团队便从零开始编码,最终交付一套高度定制化的系统。这种模式看似灵活,实则代价高昂: * 代码无法复用:相似功能(如用户管理、审批流、报表)在不同项目中反复重写 * 维护成本指数级增长:十个客户意味着十套独立系统,

AI绘画不求人:Z-Image Turbo本地部署全攻略,开箱即用

AI绘画不求人:Z-Image Turbo本地部署全攻略,开箱即用 你是不是也经历过这样的时刻:看到一张惊艳的AI插画,立刻打开浏览器搜教程,结果被“CUDA版本冲突”“PyTorch编译失败”“显存不足OOM”这些报错拦在门外?明明只是想画一幅水墨小景,却卡在环境配置第三步,连WebUI的界面都没见着。 别再折腾了。今天这篇不是教你“如何硬刚报错”,而是直接给你一条干净、稳定、真正能跑起来的本地部署路径——专为 Z-Image Turbo 量身定制的 Gradio + Diffusers 极速画板镜像,从下载到出图,全程无需改一行代码、不装一个依赖、不碰一次终端命令。它不是“理论上可行”的方案,而是我亲手在RTX 4060、RTX 3090、甚至16GB显存的MacBook Pro(M3 Max + Metal后端)上反复验证过的“开箱即用”方案。 更关键的是,它解决了国产AI绘画模型落地最头疼的三大痛点:黑图、

企业级工作流引擎低代码开发实战指南:RuoYi-Flowable-Plus全攻略

企业级工作流引擎低代码开发实战指南:RuoYi-Flowable-Plus全攻略 【免费下载链接】RuoYi-Flowable-Plus本项目基于 RuoYi-Vue-Plus 进行二次开发扩展Flowable工作流功能,支持在线表单设计和丰富的工作流程设计能力。如果觉得这个项目不错,麻烦点个star🌟。 项目地址: https://gitcode.com/gh_mirrors/ru/RuoYi-Flowable-Plus RuoYi-Flowable-Plus是基于RuoYi-Vue-Plus二次开发的开源工作流框架,融合Flowable引擎与可视化流程设计能力,为企业级应用提供低代码工作流解决方案。本文将从项目定位、核心能力到部署实践,全方位解析这款框架的技术架构与应用场景,帮助开发者快速构建企业级工作流系统。 1. 项目定位:企业级工作流解决方案的技术选型 在数字化转型浪潮中,企业对流程自动化的需求日益迫切。RuoYi-Flowable-Plus定位为"开箱即用的企业级工作流引擎",基于成熟的Spring Boot生态与Flowable BPMN 2.0引擎,提供从流