Nginx对静态资源的Range分段下载开箱即用,无需主动开启,只需确保路径直供文件、禁用max_ranges 0/sendfile on/gzip on等干扰项,并在代理场景下透传Range/If-Range头、设置含$http_range的cache_key及proxy_cache_valid 206。

Nginx 对静态资源的 Range 分段下载(断点续传)是开箱即用的功能,但实际生效依赖配置“不破坏”而非“主动开启”。只要路径直供文件、权限正确、关键干扰项被移除,206 Partial Content 就会自动返回。
确保静态 location 直接服务文件
Range 只在 Nginx 自己读取文件时才原生支持。必须满足:
- 使用
root或alias指向真实文件路径 - 不被
rewrite、auth_basic、limit_req等指令中断处理流程 -
try_files不能 fallback 到非静态处理器(如@php或/index.php) - 文件需可读,且客户端请求的字节范围在文件长度内
例如正确写法:
location /assets/ {
alias /var/www/static/;
expires 1y;
add_header Cache-Control "public, immutable";
}关闭可能干扰 Range 的机制
以下配置若存在,会直接导致 206 失效或返回 200 整包:
-
max_ranges 0;→ 删除该行,或设为max_ranges 10; -
sendfile on;→ 小文件或不确定环境建议改为sendfile off; -
gzip on;→ 对.mp4、.zip、.iso等二进制文件,加gzip_disable "range";或在该 location 中设gzip off;
验证响应是否合规
用 curl 快速检查:
curl -I -H "Range: bytes=0-1023" https://example.com/file.mp4
成功响应应包含:
-
HTTP/1.1 206 Partial Content -
Accept-Ranges: bytes -
Content-Range: bytes 0-1023/12345678 -
Content-Length: 1024
Nginx 会自动添加 Accept-Ranges 和计算 Content-Range,无需手动 add_header。
代理场景下必须透传 Range 头
如果静态资源实际由后端(如对象存储、CDN源站)提供,Nginx 仅作反向代理,则:
- 必须显式透传请求头:
proxy_set_header Range $http_range; proxy_set_header If-Range $http_if_range;
- 缓存键要区分不同 Range:
proxy_cache_key "$uri|$http_range"; - 允许缓存 206 响应:
proxy_cache_valid 206 1h; - 避免 gzip 压缩:
gzip off;或gzip_disable "range";
不复杂但容易忽略


















