静态资源优化
约 624 字大约 2 分钟
布欧-Lewyon
2026-05-15
首页 › Nginx › 静态资源服务(在新窗口打开) › 静态资源优化
sendfile
sendfile 让数据直接从内核空间发送到网络套接字,无需经过用户空间缓冲区:
http {
sendfile on; # 默认 off,推荐 on
sendfile_max_chunk 1m; # 单次 sendfile 最大传输量
}工作原理:
不开启 sendfile: 磁盘 → 内核缓冲区 → 用户空间 → 内核 Socket → 网卡
开启 sendfile: 磁盘 → 内核缓冲区 → 内核 Socket → 网卡(零拷贝)tcp_nopush 与 tcp_nodelay
http {
sendfile on;
tcp_nopush on; # 配合 sendfile,优化大文件传输
tcp_nodelay on; # 优化小文件/实时通信
}| 指令 | 作用 | 适用场景 |
|---|---|---|
tcp_nopush | 包满才发,减少小包数量 | 大文件下载配合 sendfile |
tcp_nodelay | 立即发,不等待 | 实时交互、小请求 |
tcp_nopush和tcp_nodelay可同时开启,行为取决于场景——大文件走nopush,小包走nodelay。
open_file_cache
缓存文件描述符、文件大小、修改时间等信息:
http {
open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
}| 指令 | 说明 |
|---|---|
open_file_cache max=1000 inactive=20s | 最多缓存 1000 条,20 秒无访问则淘汰 |
open_file_cache_valid 30s | 每 30 秒检查缓存有效性 |
open_file_cache_min_uses 2 | 访问 2 次后才缓存(过滤冷文件) |
open_file_cache_errors on | 缓存文件不存在的错误(避免重复 stat) |
expires / add_header Cache-Control
# 根据文件类型设置缓存
location ~* \.(css|js)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
location ~* \.(jpg|png|gif|svg|ico)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
# HTML 文件不缓存(确保内容实时更新)
location ~* \.html$ {
expires -1;
add_header Cache-Control "no-store, no-cache, must-revalidate";
}综合静态资源配置
http {
# 基础优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
open_file_cache max=2000 inactive=30s;
open_file_cache_valid 60s;
open_file_cache_min_uses 2;
server {
listen 80;
server_name static.example.com;
root /var/www/static;
# 版本化资源(文件名含 hash)长期缓存
location ~* \.(css|js|woff2?)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# 图片资源
location ~* \.(jpg|png|gif|svg|ico|webp)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
# HTML 不缓存
location ~* \.html$ {
expires -1;
add_header Cache-Control "no-cache";
}
# 默认兜底
location / {
try_files $uri $uri/ =404;
}
}
}小结
sendfile on实现零拷贝传输,是静态文件性能最关键的优化。tcp_nopush配合 sendfile 优化大文件,tcp_nodelay优化小请求。open_file_cache缓存文件元数据(描述符/大小),减少磁盘 stat 调用。expires/Cache-Control设置浏览器缓存策略,版本化资源设长缓存。- 静态文件服务器专用域名
static.example.com便于定位和扩展 CDN。
上一节:index、try_files 与目录列表 下一节:反向代理基础
