全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-20 7 分钟 ✍️ juanwangdev

静态文件服务配置

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

📝 发现内容有误?点击此处直接编辑

← 上一篇 Nginx虚拟主机配置
下一篇 → nginx events配置段
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库