nginx核心功能

一、Nginx 核心功能清单(一句话定位)

功能 解决什么问题 典型应用
静态资源服务 后端不处理图片/CSS/JS,直接由 Nginx 硬盘读取 官网、博客、前端打包产物
反向代理 隐藏后端真实 IP/端口,统一入口转发请求 Node/Java/Python 服务不暴露公网
负载均衡 多台后端分摊流量,故障自动剔除 高并发 API、微服务网关
HTTPS 终端 集中管理 SSL 证书,后端走 HTTP 减负 全站加密、HSTS 安全策略
前端路由兼容 解决 Vue/React 历史模式刷新 404 单页应用(SPA)部署
限流与安全 防刷接口、防盗链、IP 黑白名单 API 网关前置、防爬虫

二、6大功能详解 + 完整配置片段

🟢 功能1:静态资源服务 + 强缓存控制

1
2
3
4
5
6
7
# 放在 server 块内
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2|woff|ttf)$ {
root /var/www/static;
expires 30d;
add_header Cache-Control "public, immutable";
access_log off; # 静态资源不记访问日志,降低磁盘 IO
}

🔍 关键指令解析

  • root:文件实际存放路径(请求 /style.css → 读取 /var/www/static/style.css
  • expires 30d:响应头追加 Cache-Control: max-age=2592000
  • immutable:告诉浏览器“这个文件 30 天内不会变”,刷新也不重新验证
    效果验证:浏览器 Network 面板看第二次请求,状态码显示 (disk cache),耗时 <1ms

🔵 功能2:反向代理 + 真实 IP 透传

1
2
3
4
5
6
7
8
9
10
11
12
13
# 放在 server 块内
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;

# 超时优化
proxy_connect_timeout 5s;
proxy_read_timeout 30s;
proxy_send_timeout 30s;
}

🔍 关键指令解析

  • proxy_set_header:浏览器原始信息会被代理层“洗掉”,必须手动传回后端
  • X-Forwarded-For:记录完整代理链 IP(如 客户端, Nginx
  • proxy_read_timeout:后端处理慢不会直接断连(默认 60s,按需调整)
    效果验证:后端打印日志,request.remote_ip 显示你的真实公网 IP,而非 127.0.0.1

🟠 功能3:负载均衡(多后端分发)

1
2
3
4
5
6
7
8
9
10
11
12
# 放在 http 块内(server 块外部)
upstream app_pool {
server 10.0.0.11:8080 weight=3; # 性能强,扛 3/4 流量
server 10.0.0.12:8080 weight=1; # 性能弱,扛 1/4 流量
server 10.0.0.13:8080 backup; # 备用节点,其他全挂时才启用
# ip_hash; # 取消注释可开启 IP 哈希(解决 Session 丢失)
}

# 放在 server 块内
location / {
proxy_pass http://app_pool;
}

🔍 关键指令解析

  • 默认轮询(Round Robin),按 weight 比例分配
  • backup:平时不接客,仅当主节点 max_fails 失败后顶上
  • ip_hash:同一客户端 IP 固定打到同一台后端(适合无状态改造前的老系统)
    效果验证:连续刷新页面,后端日志显示请求在 10.0.0.1110.0.0.12 间按 3:1 切换

🔴 功能4:HTTPS 终端 + HTTP 强制跳转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# HTTP 兜底服务器(仅做跳转)
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}

# HTTPS 主服务器
server {
listen 443 ssl http2;
server_name example.com www.example.com;

ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

location / { root /var/www/site; index index.html; }
}

🔍 关键指令解析

  • http2:开启 HTTP/2 多路复用,提升并发加载速度
  • ssl_protocols:禁用不安全的 TLS 1.0/1.1,符合现代安全规范
  • HSTS:告诉浏览器“以后只走 HTTPS”,防降级攻击
    效果验证:访问 http://example.com 自动跳 https://;Security 面板显示 TLS 1.3

🟣 功能5:前端路由兼容(SPA 防 404)

1
2
3
4
5
location / {
root /var/www/vue-app;
index index.html;
try_files $uri $uri/ /index.html;
}

🔍 关键指令解析

  • try_files 按顺序查找:1. 精确文件 → 2. 文件夹 → 3. fallback 到 /index.html
  • Vue/React 使用 history 模式时,URL 如 /user/123 在服务器不存在,必须交给前端 JS 路由解析
    效果验证:直接访问 https://example.com/dashboard/settings 不报 404,页面正常渲染

🟤 功能6:接口限流 + 防盗链

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 1. 限流(放在 http 块)
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=5r/s;

# 2. 防盗链(放在 server 块)
location ~* \.(jpg|jpeg|png|gif|mp4)$ {
valid_referers none blocked *.example.com example.com;
if ($invalid_referer) {
return 403; # 或替换为警告图:return 302 https://example.com/warn.png;
}
root /var/www/media;
}

# 3. 应用限流(放在 server 块)
location /api/ {
limit_req zone=api_limit burst=10 nodelay;
proxy_pass http://127.0.0.1:3000;
}

🔍 关键指令解析

  • limit_req_zone:分配 10MB 内存记录 IP 请求频率,rate=5r/s 表示每秒 5 次
  • burst=10 nodelay:允许瞬间突发 10 个请求,不排队直接处理,超过则 503
  • valid_referers:只允许本站或空 referer 访问图片,其他域名嵌入直接拦截
    效果验证:用 curl -H "Referer: http://evil.com" https://example.com/img.jpg 返回 403

三、📦 生产级完整配置文件演示(开箱即用)

实际部署推荐 主配置 + 站点配置分离。以下是可直接复制的结构:

📄 /etc/nginx/nginx.conf(全局主配置)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
user www-data;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /run/nginx.pid;

events {
worker_connections 1024;
multi_accept on;
}

http {
include /etc/nginx/mime.types;
default_type application/octet-stream;

# 性能优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;

# 全局压缩
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml;
gzip_min_length 1024;

# 限流内存池(供站点调用)
limit_req_zone $binary_remote_addr zone=global_api:10m rate=10r/s;

# 引入站点配置
include /etc/nginx/conf.d/*.conf;
}

📄 /etc/nginx/conf.d/myapp.conf(单站点完整配置)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# 1. 负载均衡池
upstream backend_pool {
server 127.0.0.1:3000 weight=2;
server 127.0.0.1:3001 weight=1;
server 127.0.0.1:3002 backup;
}

# 2. HTTP → HTTPS 强制跳转
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}

# 3. HTTPS 主站
server {
listen 443 ssl http2;
server_name example.com www.example.com;

ssl_certificate /etc/ssl/certs/example.com.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers on;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

access_log /var/log/nginx/example_access.log;
error_log /var/log/nginx/example_error.log;

# 前端 SPA 路由兼容
location / {
root /var/www/vue-app/dist;
index index.html;
try_files $uri $uri/ /index.html;
}

# 静态资源强缓存
location ~* \.(css|js|png|jpg|jpeg|gif|ico|woff2)$ {
root /var/www/vue-app/dist;
expires 30d;
add_header Cache-Control "public, immutable";
access_log off;
}

# 后端 API 反向代理 + 限流 + 透传
location /api/ {
limit_req zone=global_api burst=15 nodelay;

proxy_pass http://backend_pool;
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;

proxy_connect_timeout 5s;
proxy_read_timeout 30s;
proxy_send_timeout 30s;
proxy_buffering on;
}

# 自定义错误页
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html { root /usr/share/nginx/html; }

# 安全:禁止访问隐藏文件
location ~ /\. { deny all; access_log off; log_not_found off; }
}

四、🛠️ 部署与验证流程(必做)

1
2
3
4
5
6
7
8
9
10
11
# 1. 语法检查(任何修改后第一步)
sudo nginx -t

# 2. 平滑重载(不断开现有连接)
sudo systemctl reload nginx

# 3. 验证功能
curl -I http://example.com # 应返回 301 https://...
curl -I https://example.com # 应返回 200,带 Cache-Control
curl -I https://example.com/api/v1 # 应返回 200 或 502(看后端是否启动)
tail -f /var/log/nginx/error.log # 实时看报错

五、⚠️ 高频避坑清单

现象 根本原因 解决方案
改配置不生效 reload 或语法错误未拦截 nginx -t 必须全绿才 reload
后端拿到 127.0.0.1 漏传 X-Real-IP / X-Forwarded-For 补全 proxy_set_header 三件套
静态文件 403 目录权限不足或 root 路径错 chown -R www-data:www-data /var/www/
API 刷新变慢/断连 proxy_read_timeout 太小 根据后端实际响应时间调至 30s~60s
限流误杀正常用户 rate 设太低或漏加 burst 生产建议 rate=5~10r/s + burst=10~20

[up主专用,视频内嵌代码贴在这]