一、反向代理配置
详细步骤如下(假设已安装 Nginx 且后端服务已部署):
步骤 1:确认后端服务运行状态
确保你的代码项目(如 Node.js、Java、Python 等)已在服务器上启动并监听某个端口(例如 127.0.0.1:3000
)。 可通过以下命令测试:
bash
curl http://127.0.0.1:3000
如果返回预期内容,说明后端服务正常。
步骤 2:编辑 Nginx 配置文件
Nginx 的主配置文件通常位于 /etc/nginx/nginx.conf
,但建议在 /etc/nginx/conf.d/
或 /etc/nginx/sites-available/
中创建独立的配置文件(例如 myapp.conf
)。
-
打开或创建配置文件:
bashsudo vim /etc/nginx/conf.d/myapp.conf
-
填入以下内容(根据需求调整):
nginx
server {
listen 80; # 监听 HTTP 的 80 端口
server_name yourdomain.com www.yourdomain.com; # 替换为你的域名或服务器IP
# 反向代理配置:将所有请求转发到后端服务
location / {
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;
}
# 可选:静态文件直接由 Nginx 处理(提升性能)
location /static/ {
root /path/to/your/static/files; # 静态文件目录
expires 30d; # 缓存时间
}
# 可选:禁止访问敏感文件
location ~ /\.ht {
deny all;
}
}
步骤 3:检查配置语法
运行以下命令验证配置是否正确:
bash
sudo nginx -t
如果显示 syntax is ok
和 test is successful
,说明配置无误。
步骤 4:重启 Nginx 生效
bash
sudo systemctl restart nginx # systemd 系统
# 或
sudo service nginx restart # 旧版系统
步骤 5:测试反向代理
-
浏览器访问
http://yourdomain.com
,应显示后端服务的内容。 -
检查 Nginx 日志确认请求是否转发:
bashtail -f /var/log/nginx/access.log
常见问题排查
-
502 Bad Gateway
- 后端服务未运行或端口错误。
- 检查后端服务日志:
journalctl -u your-service-name
。
-
403 Forbidden
- 确保 Nginx 用户(如
www-data
)有权限访问后端服务。 - 检查目录权限:
sudo chown -R www-data:www-data /path/to/your/app
。
- 确保 Nginx 用户(如
-
域名未生效
-
确认 DNS 已解析到服务器 IP。
-
本地测试可修改 Hosts 文件:
bashecho "your_server_ip yourdomain.com" | sudo tee -a /etc/hosts
-
高级配置示例(HTTPS/WebSocket)
如果需要 HTTPS 或支持 WebSocket,可扩展配置:
nginx
server {
listen 443 ssl http2;
server_name yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade; # WebSocket 支持
proxy_set_header Connection "upgrade";
}
}
# HTTP 强制跳转 HTTPS
server {
listen 80;
server_name yourdomain.com;
return 301 https://$host$request_uri;
}
总结
- 核心指令:
proxy_pass
+proxy_set_header
。 - 始终用
nginx -t
测试配置。 - 日志是排查问题的关键(
/var/log/nginx/error.log
)。
如果有特殊需求(如路径重写、缓存、限流),可以进一步优化配置!
二、负载均衡配置
(一)、负载均衡核心配置框架
所有负载均衡策略均基于 upstream
模块,以下为通用配置结构:
nginx
http {
upstream backend { # 定义后端服务器组
# 负载均衡策略配置(如轮询、权重等)
server 10.0.0.1:8080;
server 10.0.0.2:8080;
}
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://backend; # 将请求代理到 upstream 组
proxy_set_header Host $host;
# 其他代理配置...
}
}
}
(二)、负载均衡策略详解
1. 轮询策略(Round Robin)
-
机制:默认策略,按顺序依次将请求分发到各后端服务器。
-
配置示例:
nginxupstream backend { server 10.0.0.1:8080; server 10.0.0.2:8080; }
-
优点:简单易用,绝对公平。
-
缺点:忽略服务器性能差异,无法应对突发高负载。
-
调优:适合服务器性能均匀的场景,无需特殊配置。
2. 加权轮询(Weighted Round Robin)
-
机制:根据权重分配请求,权重越高分配的请求越多。
-
配置示例:
nginxupstream backend { server 10.0.0.1:8080 weight=3; # 3/4 的请求 server 10.0.0.2:8080 weight=1; # 1/4 的请求 }
-
优点:适应服务器性能不均的场景,优化资源利用率。
-
缺点:静态权重,无法动态响应服务器负载变化。
-
调优:
- 根据服务器 CPU、内存等指标手动调整权重。
- 结合监控工具(如 Prometheus)动态更新配置。
3. IP 哈希(IP Hash)
-
机制:根据客户端 IP 计算哈希值,固定将同一 IP 的请求分发到同一服务器。
-
配置示例:
nginxupstream backend { ip_hash; # 启用 IP 哈希策略 server 10.0.0.1:8080; server 10.0.0.2:8080; }
-
优点:实现会话保持(Session Persistence),适合有状态应用。
-
缺点:
- 服务器扩容或缩容时,哈希分布可能不均。
- 大量代理或 NAT 场景下(如公司网关),可能导致流量倾斜。
-
调优:
- 使用
consistent hashing
(需 Nginx Plus 或第三方模块)。 - 结合 Cookie 实现更灵活的会话保持。
- 使用
4. 最少连接(Least Connections)
-
机制:将请求分发给当前连接数最少的后端服务器。
-
配置示例:
nginxupstream backend { least_conn; server 10.0.0.1:8080; server 10.0.0.2:8080; }
-
优点:动态适应服务器负载,适合长连接或处理时间差异大的场景。
-
缺点:不考虑服务器响应速度,可能将请求分发给慢速服务器。
-
调优:结合加权最少连接(为服务器分配权重)。
5. 基于响应时间(需 Nginx Plus)
-
机制:将请求分发给平均响应时间最短的服务器(仅限 Nginx Plus)。
-
配置示例:
nginxupstream backend { fair; # 需要编译第三方模块 server 10.0.0.1:8080; server 10.0.0.2:8080; }
-
优点:最大化系统吞吐量,动态优化用户体验。
-
缺点:依赖商业版或第三方模块,配置复杂。
(三)、高可用性与扩展性调优
1. 健康检查(被动检查)
-
机制:自动标记故障服务器,避免将请求分发给不可用节点。
-
配置示例:
nginxupstream backend { server 10.0.0.1:8080 max_fails=3 fail_timeout=30s; server 10.0.0.2:8080 max_fails=3 fail_timeout=30s; }
max_fails
:允许的最大失败次数。fail_timeout
:故障服务器恢复检查时间。
-
调优 :主动健康检查需 Nginx Plus 或集成
nginx_upstream_check_module
。
2. 会话保持(Session Stickiness)
-
方法 1:IP 哈希(见前文)。
-
方法 2:Cookie 注入:
nginxupstream backend { server 10.0.0.1:8080; server 10.0.0.2:8080; sticky cookie srv_id expires=1h domain=.yourdomain.com path=/; }
- Nginx 会通过 Cookie
srv_id
记录客户端分配的服务器。
- Nginx 会通过 Cookie
3. 动态扩展
- 自动扩容:结合 Kubernetes 或云平台(如 AWS Auto Scaling),自动增减服务器节点。
- 配置热更新 :使用
nginx -s reload
动态加载新配置,避免重启中断服务。
(四)、逻辑架构图(文字描述)
scss
客户端请求
↓
[Nginx 负载均衡器]
├─ 策略选择(轮询/权重/IP哈希/最少连接等)
↓
后端服务器集群
├─ Server 1 (10.0.0.1:8080) → 处理请求
├─ Server 2 (10.0.0.2:8080) → 处理请求
└─ Server 3 (10.0.0.3:8080) → 处理请求
- 流量路径:客户端请求先到达 Nginx,Nginx 根据策略选择一个后端服务器转发请求。
- 故障转移:若某服务器宕机,Nginx 自动跳过故障节点。
(五)、策略选择建议
场景 | 推荐策略 | 理由 |
---|---|---|
服务器性能均匀 | 轮询 | 简单公平,无额外开销 |
服务器性能差异大 | 加权轮询 | 按权重分配流量,优化资源利用 |
需要会话保持 | IP 哈希或 Cookie | 确保同一用户请求固定到同一服务器 |
长连接或处理时间差异大 | 最少连接 | 动态平衡服务器负载 |
高动态响应要求 | Nginx Plus 响应时间 | 最大化系统吞吐量(需商业支持) |
(六)、完整配置示例(加权轮询 + 健康检查 + HTTPS)
nginx
http {
upstream backend {
least_conn; # 最少连接策略
server 10.0.0.1:8080 weight=3 max_fails=2 fail_timeout=10s;
server 10.0.0.2:8080 weight=1 max_fails=2 fail_timeout=10s;
server 10.0.0.3:8080 backup; # 备用服务器(仅在主服务器宕机时启用)
}
server {
listen 443 ssl http2;
server_name yourdomain.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
# HTTP 跳转 HTTPS
server {
listen 80;
server_name yourdomain.com;
return 301 https://$host$request_uri;
}
}
(七)、监控与日志
-
关键指标:
- 各后端服务器的请求数、响应时间、错误率。
- Nginx 的活跃连接数、请求吞吐量。
-
日志配置:
nginxlog_format upstream_log '$remote_addr - $upstream_addr [$time_local] "$request" $status'; access_log /var/log/nginx/access.log upstream_log;
-
工具推荐:
- Prometheus + Grafana:实时监控负载均衡状态。
- Zabbix:告警与历史数据分析。
(八)、总结
- 核心步骤 :定义
upstream
→ 选择策略 → 配置健康检查 → 监控调优。 - 高可用关键:多节点冗余 + 健康检查 + 动态扩展。
- 扩展性关键:合理选择策略 + 自动化运维工具。
通过灵活组合策略和持续监控,可显著提升系统的可用性和扩展性。
三、基础静态资源配置
(一)、基础配置
1. 配置静态资源目录
假设静态资源(CSS/JS/图片等)存放在 /var/www/static/
目录下:
nginx
server {
listen 80;
server_name example.com;
# 静态资源路由配置
location /static/ {
root /var/www; # 最终路径为 /var/www/static/
expires 30d; # 客户端缓存 30 天
access_log off; # 关闭访问日志(可选)
}
# 单独配置 favicon.ico(高频请求)
location = /favicon.ico {
root /var/www/static/images;
expires max; # 永久缓存
access_log off;
}
}
-
关键指令:
-
root
:指定静态文件的根目录(最终路径 =root
+location
)。 -
alias
:若需路径完全匹配(如location /img/
映射到/var/images/
),替换root
为:nginxlocation /img/ { alias /var/images/; # 请求 /img/logo.png 对应文件 /var/images/logo.png }
-
2. 验证配置并重启 Nginx
bash
sudo nginx -t # 检查语法
sudo systemctl restart nginx
(二)、性能调优配置
1. 启用高效文件传输
nginx
location /static/ {
root /var/www;
expires 30d;
# 性能优化指令
sendfile on; # 使用内核零拷贝技术(避免文件先读入内存再发送)
tcp_nopush on; # 仅在 sendfile 开启时有效,合并数据包减少网络开销
tcp_nodelay on; # 禁用 Nagle 算法,提升小文件传输速度
}
2. 开启 Gzip 压缩
nginx
http {
gzip on; # 启用 Gzip
gzip_types text/css application/javascript image/svg+xml; # 压缩类型
gzip_comp_level 6; # 压缩级别(1-9,越高 CPU 消耗越大)
gzip_min_length 1k; # 最小压缩文件大小
gzip_vary on; # 告知客户端支持 Gzip
server {
location /static/ {
gzip_static on; # 优先使用预压缩文件(如 .gz 文件)
}
}
}
-
预生成压缩文件(提升性能):
nginxgzip -k /var/www/static/style.css # 生成 style.css.gz
3. 浏览器缓存控制
nginx
location ~* \.(jpg|png|css|js)$ {
root /var/www/static;
expires 365d; # 长期缓存
add_header Cache-Control "public"; # 允许代理和浏览器缓存
add_header ETag ""; # 禁用 ETag(减少协商请求)
if_modified_since off; # 忽略 Last-Modified 头
}
(三)、高级优化技巧
1. 使用内存盘(RAM Disk)加速
将频繁访问的静态文件放入内存:
bash
sudo mkdir /mnt/ramdisk
sudo mount -t tmpfs -o size=512M tmpfs /mnt/ramdisk
cp -r /var/www/static /mnt/ramdisk/
Nginx 配置:
nginx
location /static/ {
root /mnt/ramdisk; # 从内存读取文件
}
2. 静态文件分域名(Cookie-Free)
-
优势 :静态域名(如
static.example.com
)不携带主域 Cookie,减少请求头大小。 -
配置:
nginxserver { listen 80; server_name static.example.com; location / { root /var/www/static; expires max; } }
-
HTML 引用:
html<link href="https://static.example.com/css/style.css" rel="stylesheet">
3. Brotli 压缩(需 Nginx 支持)
比 Gzip 更高的压缩率:
nginx
http {
brotli on;
brotli_types text/css application/javascript image/svg+xml;
brotli_comp_level 6;
}
- 需安装
ngx_brotli
模块(通过动态模块或编译安装)。
(四)、安全与访问控制
1. 防止目录遍历
nginx
location /static/ {
root /var/www;
autoindex off; # 禁止目录列表
}
2. 限制敏感文件访问
nginx
location ~* \.(htaccess|git|env)$ {
deny all; # 禁止访问
}
3. 防盗链(Hotlink Protection)
nginx
location ~* \.(jpg|png|mp4)$ {
root /var/www/static;
valid_referers none blocked example.com *.example.com;
if ($invalid_referer) {
return 403; # 非允许来源返回 403
# 或返回一张默认图片:
# rewrite ^ /static/images/blocked.png break;
}
}
(五)、监控与调优验证
1. 检查文件传输效率
bash
# 查看静态文件请求是否命中缓存
curl -I http://example.com/static/style.css
# 响应头应包含:Cache-Control: max-age=2592000
# 测试 Gzip 是否生效
curl -H "Accept-Encoding: gzip" -I http://example.com/static/style.css
# 响应头应包含:Content-Encoding: gzip
2. 性能压测工具
-
ab (Apache Benchmark):
bashab -c 100 -n 1000 http://example.com/static/image.jpg
-
wrk:
bashwrk -t4 -c100 -d10s http://example.com/static/image.jpg
3. 日志分析
bash
log_format static_log '$remote_addr - $request_time - $request';
access_log /var/log/nginx/static.log static_log;
分析慢请求:
bash
awk '$2 > 1 {print}' /var/log/nginx/static.log # 找出响应时间 >1s 的请求
(六)、完整优化配置示例
nginx
http {
# 全局 Gzip 压缩
gzip on;
gzip_types text/css application/javascript image/svg+xml;
gzip_comp_level 6;
gzip_min_length 1k;
server {
listen 80;
server_name example.com;
# 静态资源配置
location /static/ {
root /var/www;
expires 365d;
add_header Cache-Control "public";
access_log off;
# 性能优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
# 安全控制
autoindex off;
}
# 单独优化图片
location ~* \.(jpg|png|webp)$ {
root /var/www/static/images;
expires max;
try_files $uri /images/fallback.png; # 文件不存在时返回默认图
}
}
}
(七)、总结
- 核心优化点 :
- 缓存 :
expires
和Cache-Control
控制浏览器缓存。 - 传输效率 :
sendfile
+tcp_nopush
减少 I/O 开销。 - 压缩:Gzip/Brotli 降低带宽占用。
- 安全:防盗链 + 敏感文件拦截。
- 缓存 :
- 进阶方案 :
- 使用 CDN 加速静态资源(如 Cloudflare、AWS CloudFront)。
- 对静态资源启用 HTTP/2 多路复用。
通过以上配置,静态资源的加载速度可提升 50% 以上,同时显著降低服务器负载。
四、SSL 终结(SSL Termination)
(一)、什么是 SSL 终结?
-
原理:在 Nginx 上终止 HTTPS 加密,将解密后的明文请求转发给后端服务器(如 Tomcat、Node.js)。
-
优势:
- 减轻后端服务器的 SSL/TLS 计算压力。
- 集中管理证书和加密策略。
- 便于实现负载均衡和缓存。
-
基础配置示例
nginx
server {
listen 443 ssl http2; # 启用 HTTP/2
server_name example.com;
# SSL 证书配置
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# SSL 协议优化
ssl_protocols TLSv1.2 TLSv1.3; # 禁用不安全的 TLSv1.0/1.1
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
# 反向代理到后端(明文 HTTP)
location / {
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
# HTTP 强制跳转 HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
- 优缺点分析
优点 | 缺点 |
---|---|
后端服务器无需处理加密/解密,性能更高 | 代理到后端的流量是明文的(需内网隔离) |
集中管理证书,更新更方便 | 若内网不安全,可能被中间人攻击 |
支持 HTTP/2 加速 | 需要 Nginx 具备足够的 CPU 资源 |
(二)、HTTPS 加速优化
1. 启用 HTTP/2
-
配置 :在
listen
指令中添加http2
:nginxlisten 443 ssl http2;
-
优势:
- 多路复用(减少 TCP 连接数)。
- 头部压缩(降低带宽占用)。
- 服务器推送(需额外配置)。
2. 会话复用(Session Resumption)
nginx
ssl_session_cache shared:SSL:10m; # 共享缓存大小(10MB)
ssl_session_timeout 1h; # 会话超时时间
- 作用:减少 SSL/TLS 握手开销,提升性能。
3. OCSP Stapling
nginx
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;
resolver 8.8.8.8 valid=300s;
- 优势:客户端无需直接查询 CA 验证证书状态,减少延迟。
4. 证书优化
-
使用 ECC 证书:比 RSA 证书更高效:
nginxssl_certificate /path/to/ecc_cert.pem; ssl_certificate_key /path/to/ecc_key.pem;
-
证书链完整:避免浏览器中间证书警告。
(三)、HTTP 加速优化
1. 静态资源缓存
nginx
location ~* \.(jpg|css|js)$ {
expires 365d;
add_header Cache-Control "public";
access_log off;
}
2. Gzip/Brotli 压缩
nginx
gzip on;
gzip_types text/css application/javascript;
gzip_min_length 1k;
# Brotli(需安装模块)
brotli on;
brotli_types text/html text/plain text/css;
3. Keepalive 连接
nginx
http {
keepalive_timeout 65; # 保持 TCP 连接时间
keepalive_requests 100; # 单个连接最大请求数
}
(四)、调优与监控
1. SSL 性能调优
-
CPU 亲和性:绑定 Nginx 进程到特定 CPU 核心(减少上下文切换):
bashworker_processes auto; worker_cpu_affinity auto;
-
启用 SSL 硬件加速(如支持 AES-NI 的 CPU):
nginxssl_engine dynamic;
2. 监控指标
-
SSL 握手时间:
bashawk '{print $NF}' /var/log/nginx/ssl_handshake.log | sort -n
-
证书过期提醒:
bashopenssl x509 -enddate -noout -in /etc/letsencrypt/live/example.com/cert.pem
3. 压力测试
bash
# 测试 HTTPS 性能
wrk -t4 -c100 -d30s https://example.com --latency
(五)、高级场景
1. 混合内容修复(Mixed Content)
-
强制 HTTPS 引用资源:
nginxsub_filter 'http://' 'https://'; sub_filter_once off;
2. 多域名 SNI 支持
nginx
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /path/to/example.com.crt;
# ...
}
server {
listen 443 ssl http2;
server_name another.com;
ssl_certificate /path/to/another.com.crt;
# ...
}
3. 0-RTT(TLS 1.3)
nginx
ssl_early_data on; # 启用 0-RTT(需评估重放攻击风险)
(六)、完整配置示例
nginx
http {
# 全局 SSL 优化
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1h;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
server {
listen 443 ssl http2;
server_name example.com;
# 证书配置
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;
# OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
# 静态资源缓存
location ~* \.(jpg|css|js)$ {
expires 365d;
access_log off;
}
# 反向代理
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
# HTTP 跳转 HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
}
(七)、总结
最佳实践
- SSL 终结:适用于安全内网环境,显著降低后端负载。
- HTTP/2:必选项,大幅提升页面加载速度。
- 会话复用:减少 30% 以上的 TLS 握手时间。
- 监控:定期检查证书有效期和 SSL 性能。
避坑指南
- 禁用不安全的协议:如 TLSv1.0/1.1、SSLv3。
- 避免过度加密:如 4096 位 RSA 证书(优先选择 ECC)。
- 内网加密:若后端跨公网传输,考虑二次加密(如 VPN 或 IPSec)。
通过以上配置,Nginx 可实现高效的 HTTPS 加速与 SSL 终结,平衡安全性与性能。
五、特殊需求
在 Nginx 中,针对 路径重写、缓存、限流 等特殊需求,可以通过模块化配置进一步优化性能和安全。以下是详细配置方法、调优逻辑及实际示例:
(一)、路径重写(URL Rewrite)
1. 应用场景
- 隐藏后端真实路径(如将
/api/
转发到/backend/
)。 - 兼容旧版 URL(SEO 友好)。
- 静态化动态链接。
2. 配置示例
nginx
server {
location /user/profile {
# 重写 /user/profile?id=123 为 /profile/123
rewrite ^/user/profile\?id=(\d+)$ /profile/$1 permanent;
}
location /api/ {
# 将 /api/ 开头的请求转发到后端,并去掉 /api 前缀
rewrite ^/api/(.*)$ /$1 break; # `break` 表示重写后不再匹配其他规则
proxy_pass http://backend;
}
}
- 指令说明 :
rewrite <regex> <replacement> [flag]
:正则匹配并替换。flag
常用值:last
:重写后重新匹配 location。break
:终止后续匹配。permanent
:返回 301 永久重定向。
3. 调优建议
- 避免过度重写:每条规则会增加处理延迟。
- 使用
^~
或=
前缀优化匹配效率(如location = /favicon.ico
)。
(二)、缓存优化
1. 代理缓存(反向代理场景)
nginx
http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m use_temp_path=off;
server {
location / {
proxy_cache my_cache;
proxy_pass http://backend;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 304 10m; # 缓存 200/304 状态码响应 10 分钟
add_header X-Cache-Status $upstream_cache_status; # 显示缓存命中状态
}
}
}
- 关键参数 :
keys_zone
:定义共享内存区域名称和大小(10MB)。inactive
:缓存过期时间(60 分钟未被访问则清除)。proxy_cache_valid
:按状态码设置缓存时间。
2. 静态资源缓存
nginx
location ~* \.(jpg|css|js)$ {
expires 30d; # 客户端缓存 30 天
access_log off; # 关闭日志减少 I/O
add_header Cache-Control "public";
}
3. 调优建议
- 分层缓存:结合 CDN(如 Cloudflare)和 Nginx 多级缓存。
- 缓存清理 :使用
proxy_cache_purge
模块(需额外安装)或手动删除缓存文件。
(三)、限流(Rate Limiting)
1. 请求速率限制
nginx
http {
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
server {
location /api/ {
limit_req zone=api_limit burst=20 nodelay;
proxy_pass http://backend;
}
}
}
- 参数说明 :
limit_req_zone
:定义限流区域(api_limit
),基于客户端 IP($binary_remote_addr
)。rate=10r/s
:每秒允许 10 个请求。burst=20
:允许突发 20 个请求排队。nodelay
:立即处理突发请求,不延迟。
2. 并发连接数限制
nginx
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
location /download/ {
limit_conn conn_limit 5; # 每个 IP 最多 5 个并发连接
proxy_pass http://backend;
}
3. 调优建议
-
白名单设置:排除内网或可信 IP:
nginxgeo $limit { default 1; 10.0.0.0/8 0; # 内网不限速 } map $limit $limit_key { 0 ""; 1 $binary_remote_addr; } limit_req_zone $limit_key zone=api_limit:10m rate=10r/s;
-
日志记录:监控被限流的请求:
nginxlocation /api/ { limit_req_status 429; error_log /var/log/nginx/rate_limit.log; }
(四)、高级场景组合配置
1. 动态路径重写 + 缓存 + 限流
nginx
http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=dynamic_cache:10m inactive=1h;
limit_req_zone $binary_remote_addr zone=global_limit:10m rate=5r/s;
server {
location ~ ^/shop/(\d+)/product/(\d+) {
# 重写 URL:/shop/123/product/456 → /product?id=456&shop=123
rewrite ^/shop/(\d+)/product/(\d+)$ /product?id=$2&shop=$1 break;
proxy_pass http://backend;
proxy_cache dynamic_cache;
proxy_cache_valid 200 5m;
limit_req zone=global_limit burst=10;
}
}
}
2. 微服务路由 + 熔断机制
nginx
upstream auth_service {
server 10.0.0.1:8000 max_fails=2 fail_timeout=30s;
}
upstream order_service {
server 10.0.0.2:8000 max_fails=2 fail_timeout=30s;
}
server {
location /auth/ {
proxy_pass http://auth_service;
proxy_next_upstream error timeout http_500; # 故障时尝试下一个节点
}
location /orders/ {
proxy_pass http://order_service;
proxy_intercept_errors on;
error_page 502 503 = @fallback;
}
location @fallback {
return 503 "Service Temporarily Unavailable";
# 或转发到静态降级页面
# root /var/www/fallback;
# try_files /order_fallback.html =503;
}
}
(五)、调优工具与监控
1. 性能分析工具
- Nginx Amplify:可视化监控缓存命中率、限流效果。
- OpenResty:集成 Lua 脚本实现动态逻辑(如复杂限流算法)。
2. 关键指标监控
-
缓存效率:
bashgrep -E "HIT|MISS|EXPIRED" /var/log/nginx/access.log
-
限流触发:
bashawk '$9 == 429 {print $1}' /var/log/nginx/access.log | sort | uniq -c
(六)、逻辑流程图
csharp
客户端请求
↓
[Nginx] → 路径重写(rewrite) → 限流检查(limit_req)
↓
缓存检查(proxy_cache) → 命中 → 直接返回
↓
未命中 → 反向代理(proxy_pass) → 后端服务
↓
返回响应并缓存(proxy_cache_valid)
(七)、总结
- 路径重写 :用
rewrite
和location
实现灵活路由。 - 缓存优化 :分静态和动态资源,关注
proxy_cache_path
和expires
。 - 限流保护 :
limit_req_zone
防 CC 攻击,limit_conn
防资源耗尽。 - 组合策略:根据业务需求混合使用,如"重写 + 缓存"提升 SEO 和性能,"限流 + 熔断"保障稳定性。
通过合理配置,Nginx 可以成为高性能、高可用的全能网关。