前端必知: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

【保姆级教程】无成本零门槛安装配置OpenClaw龙虾AI全能助手

【保姆级教程】无成本零门槛安装配置OpenClaw龙虾AI全能助手

哈喽大家好!最近爆火的 OpenClaw(龙虾AI)全能助手大家体验了吗?它不仅能帮你自动整理邮件、查询天气,还能全自动写小红书笔记并发布,简直是打工人和自媒体人的摸鱼神器! 很多小伙伴想玩但又怕配置太复杂、花销太大。今天给大家带来一篇零门槛、保姆级的安装配置教程!教你如何低成本获取云服务器,轻松实现 AI 大模型自由。全程图文指引,小白也能轻松搞定,赶紧跟着操作起来吧! 一、获取云服务器 想要畅玩 OpenClaw,首先我们需要一个服务器。这次教大家如何获取腾讯云轻量服务器来进行配置。 ⏰ 活动时间:2026年1月21日 - 3月31日 腾讯推出了登录 CodeBuddy 送 2C2G4M 轻量服务器的限时活动:登录先送1个月,活跃7天再送2个月。 👉 【官方地址】:https://www.codebuddy.cn/promotion/?ref=ie2rwhd1loq 根据页面提示安装好软件并登录账号后,直接选择一个月的轻量应用服务器即可。 之后只要累计活跃7天就能续费两个月(每天和 AI

AI赋能专利翻译,八月瓜科技“妙算翻译大模型”亮相国际论坛

AI赋能专利翻译,八月瓜科技“妙算翻译大模型”亮相国际论坛

当前,国家高度重视人工智能与知识产权融合发展,《新一代人工智能发展规划》明确提出“推动人工智能在知识产权检索、分析、翻译等领域的深度应用,提升知识产权服务效率与质量”,《“十四五”国家知识产权保护和运用规划》也强调“加强知识产权信息化、智能化基础设施建设,推动专利信息跨语言互通”。 顺应这一政策导向,专利领域对专业化翻译的需求愈发迫切。八月瓜科技“妙算翻译大模型”立足需求,凭借深厚的技术积累与精准的场景适配,成为破解行业痛点、助力跨境创新的核心力量。 国际论坛亮相获认可,产品实力彰显初心 日前,妙算翻译大模型凭借在专利翻译领域的突出实力与创新成果,亮相东盟+中日韩(10+3)人工智能产业发展论坛,成为论坛上聚焦知识产权服务智能化的亮点成果,获得了行业专家、参会企业及相关机构的高度关注与广泛认可。此次论坛亮相,不仅是对妙算翻译大模型技术实力与应用价值的权威肯定,更彰显了其在推动专利翻译智能化、打破跨国创新语言壁垒方面的重要作用,为其进一步拓展市场、服务更多科技创新主体奠定了坚实基础。 能获得行业广泛认可,核心源于产品本身的专业定位与硬核实力。妙算翻译大模型在语言

字节开源 DeerFlow 2.0——登顶 GitHub Trending 1,让 AI 可做任何事情

字节开源 DeerFlow 2.0——登顶 GitHub Trending 1,让 AI 可做任何事情

打开 deerflow 的官网,瞬间被首页的这段文字震撼到了,do anything with deerflow。让 agent 做任何事情,这让我同时想到了 openclaw 刚上线时场景。 字节跳动将 DeerFlow 彻底重写,发布 2.0 版本,并在发布当天登上 GitHub Trending 第一名。这不是一次功能迭代,而是一次从"深度研究框架"到"Super Agent 运行时基础设施"的彻底蜕变。 背景:从 v1 到 v2,发生了什么? DeerFlow(Deep Exploration and Efficient Research Flow)

Flutter 组件 tavily_dart 的适配 鸿蒙Harmony 深度进阶 - 驾驭 AI 原生聚合搜索、实现鸿蒙端跨域知识发现与垂直领域语义降噪方案

Flutter 组件 tavily_dart 的适配 鸿蒙Harmony 深度进阶 - 驾驭 AI 原生聚合搜索、实现鸿蒙端跨域知识发现与垂直领域语义降噪方案

欢迎加入开源鸿蒙跨平台社区:https://openharmonycrossplatform.ZEEKLOG.net Flutter 组件 tavily_dart 的适配 鸿蒙Harmony 深度进阶 - 驾驭 AI 原生聚合搜索、实现鸿蒙端跨域知识发现与垂直领域语义降噪方案 前言 在前文中,我们领略了 tavily_dart 在鸿蒙(OpenHarmony)生态中实现基础互联网 AI 搜索集成的魅力。但在真正的“跨国科研智能辅助”、“政务决策舆情态势感知”以及“需要接入高精密专业数据库”的场景中。简单的单次查询往往不足以触达知识的核心。面对需要在大规模并发环境下,针对特定行业域名(如 .gov / .edu)执行深层内容的并行嗅探,并且要求对回显的数万字内容执行基于 AI 强语义的重排序(Re-ranking)与引用链路审计的高阶需求。如果缺乏一套完善的聚合搜索策略与语义降噪模型。不仅会导致 AI 智能体出现由于“信息泛滥”