前端必知: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 代理:
- 启动 Vite 项目:
npm run dev(运行在http://localhost:5173); - 前端请求
/api/user→ Nginx 转发到后端,解决跨域。
- 启动 Vite 项目:
配置 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;
- Mac:
- 服务器配置文件路径:
/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; #} }