📄 前后端 + Nginx + 请求流程完整理解(总结版) / The Complete Request Path from Browser to Backend Through Nginx
🧩 一、环境设定
(1) 🖥 服务器A(前端 + 网关)
- IP:
1.1.1.1 - 域名:
A.com - 包含:
- Nginx(监听
80 / 443) - 前端代码(
HTML / JS)
- Nginx(监听
(2) 🖥 服务器B(后端)
- IP:
2.2.2.2 - 包含:
- Node.js(监听
3000)
- Node.js(监听
(3) 🧠 Nginx 配置(在服务器A)
nginx
server {
listen 443;
server_name A.com;
location / {
root /frontend;
index index.html;
try_files $uri /index.html;
}
location /api/ {
proxy_pass http://2.2.2.2:3000;
}
}🚀 二、完整请求流程(一步一步)
🟢 第一步:用户输入网址
- 输入:
https://A.com - 发生在:
【用户电脑(浏览器)】 - 浏览器行为:
A.com → DNS → 1.1.1.1https → 443
- 最终连接:
1.1.1.1:443
🟢 第二步:请求页面(前端)
- 浏览器发送:
http
GET /
Host: A.com- 到达:
【服务器A(1.1.1.1)】的 Nginx - Nginx 处理:
location / - 返回:
/frontend/index.html - 返回给:
【浏览器】
🟢 第三步:前端代码运行
- 发生在:
【浏览器】 - 执行 JS:
js
fetch('/api/user')🟢 第四步:请求后端数据(关键)
- 浏览器发送:
http
GET /api/user
Host: A.com- 到达:
【服务器A(1.1.1.1)】的 Nginx - Nginx 判断路径:
/api → 命中 location /api/ - Nginx 转发请求:
http://2.2.2.2:3000
🟢 第五步:后端处理
- 到达:
【服务器B(2.2.2.2)】的 Node.js(3000端口) - 后端处理:
/api/user → 查询数据 → 返回 JSON
🟢 第六步:返回链路
- 返回路径:
服务器B(Node) → 服务器A(Nginx) → 浏览器 - 注意:👉 返回经过的是服务器A上的同一个 Nginx
🟢 第七步:浏览器更新页面
- 发生在:
【浏览器】 - 拿到数据:
json
{ "name": "张三" }- 更新 UI
🔥 三、完整链路图(终极版)
text
【用户电脑】
浏览器
↓(请求页面)
-----------------------------------
【服务器A(1.1.1.1)】
Nginx
↓
返回 index.html
-----------------------------------
【浏览器】
运行前端代码
↓(点击按钮)
↓(发请求)
-----------------------------------
【服务器A】
Nginx
↓(proxy)
-----------------------------------
【服务器B(2.2.2.2)】
Node.js
↓(返回数据)
-----------------------------------
【服务器A】
Nginx
↓
-----------------------------------
【浏览器】
渲染数据🔥 四、关键知识点总结(必须记住)
- 浏览器才是发请求的人。前端代码只是触发:
fetch(...) - Nginx 在服务器A(
1.1.1.1),所有请求先到这里(网关)。 - 浏览器不会直接访问后端服务器:
2.2.2.2❌(不会直接访问)。 /api只是路径,不是服务器地址:/api/user ≠ 后端服务器。- 端口是服务器决定的:
Nginx listen 443 → 浏览器才能连 443。 - 请求是“链式传递”:
浏览器 → Nginx → 后端 → Nginx → 浏览器。
🔥 五、终极一句话总结
浏览器请求 A.com → 到 1.1.1.1 的 Nginx → Nginx 转发到 2.2.2.2 → 后端处理 → 返回数据。