# nginx中文件下载指定保存文件名怎么配置 ## 前言 在Web服务中,文件下载是常见的功能需求。默认情况下,浏览器会根据URL的最后一部分作为下载文件名,但有时我们需要动态指定更友好的文件名。本文将详细介绍如何在nginx中通过配置实现下载文件时指定保存文件名。 --- ## 一、默认下载行为分析 当用户访问 `http://example.com/files/document.pdf` 时: 1. 浏览器会自动将文件名保存为 `document.pdf` 2. 若URL不含文件名(如通过API接口返回文件),则可能保存为无意义的随机字符串 --- ## 二、核心配置指令:`add_header Content-Disposition` 通过设置HTTP响应头的 `Content-Disposition` 字段可以控制下载行为: ```nginx location /download/ { add_header Content-Disposition 'attachment; filename="custom_name.pdf"'; }
attachment
:强制浏览器下载而非直接打开filename
:指定客户端保存时使用的文件名location ~ ^/download/(.*)$ { add_header Content-Disposition 'attachment; filename="$1"'; alias /var/files/; }
当访问 /download/report2023.xlsx
时: - 实际文件路径:/var/files/report2023.xlsx
- 下载保存名:report2023.xlsx
location /download { rewrite ^/download/(.*)$ /real_files/$1; add_header Content-Disposition 'attachment; filename="$1"'; }
location /api/download { if ($arg_filename) { add_header Content-Disposition 'attachment; filename="$arg_filename"'; } alias /var/files/; }
访问URL示例:/api/download?file=data.db&filename=backup.db
直接使用中文会出现乱码:
add_header Content-Disposition 'attachment; filename="中文文件.txt"';
使用RFC 5987编码:
add_header Content-Disposition 'attachment; filename*=UTF-8''%E4%B8%AD%E6%96%87%E6%96%87%E4%BB%B6.txt';
server { listen 80; server_name example.com; # 静态文件下载 location /static/ { alias /data/files/; add_header Content-Disposition 'attachment; filename="$uri"'; } # 动态生成文件下载 location /export { fastcgi_pass backend; add_header Content-Disposition 'attachment; filename="export_data.csv"'; } # 带参数的文件下载 location /download { if ($arg_fname) { add_header Content-Disposition 'attachment; filename="$arg_fname"'; } alias /data/archives/; } }
安全限制:确保文件名参数经过过滤,防止目录遍历攻击
if ($arg_filename ~* "\.\.") { return 403; }
MIME类型:建议同时配置正确的Content-Type
types { application/octet-stream .bin; }
浏览器兼容性:
性能影响:大量小文件下载时建议开启sendfile
sendfile on;
通过合理配置 Content-Disposition
响应头,nginx可以灵活控制文件下载时的保存文件名。实际部署时建议结合业务场景选择静态配置或动态方案,并注意做好安全防护。对于更复杂的需求,还可以考虑结合Lua脚本等扩展实现。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。