有一个需求: 对静态文件如 .txt 等后缀,直接下载而不是在浏览器中打开。

网上找到的解决方案是:

添加头信息Content-Disposition "attachment;"会使浏览器强制下载:

if ($request_filename ~* ^.*?\.(txt|pdf|doc|xls)$){  
      add_header Content-Disposition "attachment;";
}

但添加该配置后,使用 nginx -t 检测发现报错:

nginx: [emerg] "add_header" directive is not allowed here

就是说,这个地方是不允许使用 add_header 指令的,位置放错了。

解决方法

我是直接加在 server{ ... } 配置里面的,检查测试后发现,需要加在 location 标签里,于是套了一层,配置就变成了:

server {
    // 其他配置...

    location / {
        if ($request_filename ~* ^.*?\.(txt|pdf|doc|xls)$){  
              add_header Content-Disposition "attachment;";
        }
    }
    // 其他配置...
}

保存重启 Nginx 后问题解决,指定文件转附件直接下载的需求也没问题。

总结,Nginx 的 add_header 命令必须要放在 location 下面。

标签: txt, 文件下载