静态文件服务配置
Nginx 作为静态文件服务器性能优异,下面梳理核心配置项与优化实践。
基本配置
nginx
server {
listen 80;
server_name static.example.com;
location / {
root /data/static;
index index.html;
}
}
核心指令
root 与 alias
nginx
# root:拼接 location 路径
# 请求 /files/logo.png → /data/files/logo.png
location /files/ {
root /data;
}
# alias:替换 location 路径
# 请求 /files/logo.png → /var/www/static/logo.png
location /files/ {
alias /var/www/static/;
}
try_files
按顺序尝试文件,最终 fallback 到指定路径:
nginx
location / {
try_files $uri $uri/ /index.html;
}
用于 SPA 单页应用路由,所有未匹配路径返回 index.html。
默认文件
nginx
index index.html index.htm index.php;
静态资源优化
sendfile 零拷贝
nginx
sendfile on;
tcp_nopush on;
tcp_nodelay on;
| 指令 | 作用 |
|---|---|
sendfile on | 启用内核级零拷贝,减少用户态/内核态切换 |
tcp_nopush on | 配合 sendfile,数据包达到最大大小后发送 |
tcp_nodelay on | 禁用 Nagle 算法,小数据包立即发送 |
缓存控制
nginx
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
root /data/static;
expires 30d;
add_header Cache-Control "public, no-transform";
access_log off;
}
压缩传输
nginx
http {
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml;
gzip_min_length 256;
gzip_comp_level 6;
gzip_vary on;
}
| 指令 | 说明 |
|---|---|
gzip on | 启用压缩 |
gzip_types | 压缩的 MIME 类型 |
gzip_min_length | 最小压缩大小(字节) |
gzip_comp_level | 压缩级别 1-9,值越大压缩率越高但更耗 CPU |
gzip_vary on | 添加 Vary: Accept-Encoding 头 |
防盗链配置
nginx
location ~* \.(jpg|jpeg|png|gif)$ {
valid_referers none blocked server_names *.example.com;
if ($invalid_referer) {
return 403;
# 或返回替代图片:rewrite ^/ /images/forbidden.png break;
}
}
目录浏览
nginx
location /downloads/ {
root /data;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
}
注意事项
autoindex暴露目录结构,生产环境谨慎开启- 图片等已压缩格式(jpg、png)无需再次 gzip
expires设置后浏览器缓存期间不发起请求,需更新资源时建议加版本号- 防盗链基于 Referer 头,可被伪造,仅作为基础防护
大文件下载优化
nginx
location /downloads/ {
root /data;
aio on;
directio 4m;
output_buffers 1 128k;
}
| 指令 | 说明 |
|---|---|
aio on | 启用异步 I/O |
directio 4m | 大于 4MB 的文件直接 I/O,绕过缓存 |
output_buffers | 输出缓冲区配置 |
要点总结
- root 拼接路径,alias 替换路径,两者作用不同
- try_files 按顺序尝试文件,适用于 SPA 路由
- sendfile、tcp_nopush、tcp_nodelay 组合优化文件传输性能
- gzip 压缩减少传输体积,图片等已压缩格式无需开启
- expires 设置浏览器缓存,防盗链基于 Referer 头校验
- 大文件服务可开启 aio 和 directio 优化 I/O
📝 发现内容有误?点击此处直接编辑