Nginx 能做什么

Nginx 是高性能 Web 服务器,日常主要承担三个角色:

  1. 静态文件服务器:直接托管前端打包产物;
  2. 反向代理:把请求转发给后端服务(Node/Java/Python),对外只暴露 Nginx;
  3. 负载均衡:把请求分发到多台后端服务器。

一、反向代理基础配置

把 /api 开头的请求转发到本机 3000 端口的 Node 服务:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
server {
listen 80;
server_name example.com;

# 前端静态文件
location / {
root /var/www/myapp/dist;
index index.html;
try_files $uri $uri/ /index.html; # 前端路由 history 模式必备
}

# API 反向代理
location /api/ {
proxy_pass http://127.0.0.1:3000;
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;
}
}

try_files ... /index.html 是 SPA 部署的关键:前端路由刷新时,找不到真实文件就回退到入口页。

二、location 匹配规则

写法 含义 优先级
= 精确匹配 最高
^~ 前缀匹配(匹配后不再查正则) 高
~ / ~* 正则匹配(区分/不区分大小写) 中
普通前缀 最长前缀匹配 低
1
2
3
location = /favicon.ico { log_not_found off; }   # 精确
location ^~ /static/ { expires 7d; } # 前缀优先
location ~* \.(png|jpg|css|js)$ { expires 30d; } # 正则

三、负载均衡:upstream

多台后端服务器用 upstream 定义集群:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
upstream backend {
server 10.0.0.11:8080 weight=3; # 权重 3,被分配概率更高
server 10.0.0.12:8080 weight=1;
server 10.0.0.13:8080 backup; # 备用,前面挂了才启用
keepalive 32;
}

server {
listen 80;
location /api/ {
proxy_pass http://backend;
proxy_next_upstream error timeout; # 后端出错自动换下一台
}
}

负载策略:

  • 轮询(默认):按请求轮流分发;
  • weight:按权重比例分发(适合异构服务器);
  • ip_hash:同一 IP 固定到同一台(适合需要会话保持的场景);
  • least_conn:分给当前连接数最少的服务器。

四、静态资源缓存与 gzip

1
2
3
4
5
6
7
8
9
10
11
12
# gzip 压缩
gzip on;
gzip_comp_level 5;
gzip_min_length 1k;
gzip_types text/plain text/css application/javascript application/json image/svg+xml;

# 静态资源强缓存(文件名带 hash 的资源可以放心长缓存)
location /assets/ {
alias /var/www/myapp/dist/assets/;
expires 30d;
add_header Cache-Control "public, immutable";
}

expires 30d 告诉浏览器 30 天内直接用本地缓存;文件名带 hash(如 app.8f3a2c.js)变化后自动生成新 URL,不会读到旧缓存。

五、HTTP 跳转 HTTPS(基础版)

1
2
3
4
5
6
7
8
9
10
11
12
13
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}

server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/nginx/ssl/example.com.pem;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
# ... 其余配置
}

证书申请推荐 certbot(Let’s Encrypt 免费证书),自动续期后 nginx -s reload 即可。

六、配置检查与排错

1
2
3
4
5
6
7
8
9
10
# 检查配置语法(改配置后必做)
nginx -t

# 平滑重载配置
nginx -s reload

# 常用排错
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log
curl -I http://localhost:8080/api/health

代理 502 排查顺序:后端服务是否在跑 → proxy_pass 地址端口对不对 → 防火墙是否放行 → 后端日志有没有报错。

常见坑

  1. proxy_pass 带不带斜杠语义不同:proxy_pass http://backend; 保留原路径;proxy_pass http://backend/; 会替换匹配前缀,容易踩;
  2. websocket 需要特殊头:proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade";;
  3. 客户端 IP 拿不到真实地址:没传 X-Real-IP/X-Forwarded-For,后端取到的是 Nginx 地址;
  4. 缓存了不该缓存的东西:动态接口不要 expires,在响应头用 Cache-Control: no-store 控制。

总结

Nginx 的配置核心就三块:location 怎么匹配、proxy_pass 往哪转、缓存压缩怎么开。先跑通”静态 + API 反代”的经典组合,再按需上负载均衡和 HTTPS。