插件窝 干货文章 nginx中文件下载指定保存文件名怎么配置

nginx中文件下载指定保存文件名怎么配置

文件名 filename Disposition Content 940    来源:    2025-04-21

Nginx 配置指定文件下载保存文件名

在Nginx中,你可以通过配置Content-Disposition响应头来指定文件下载时的默认保存文件名。以下是几种实现方式:

方法1:使用add_header指令

location /download/ {
    # 设置Content-Disposition头指定文件名
    add_header Content-Disposition 'attachment; filename="your-filename.ext"';

    # 其他配置...
}

方法2:使用$args或变量动态指定文件名

location /download/ {
    # 从URL参数中获取文件名
    if ($args ~* "filename=([^&]+)") {
        set $downname $1;
        add_header Content-Disposition 'attachment; filename="$downname"';
    }

    # 其他配置...
}

方法3:使用map指令映射文件名

map $uri $downname {
    ~/download/(.*) $1;
    default "";
}

server {
    location /download/ {
        if ($downname) {
            add_header Content-Disposition 'attachment; filename="$downname"';
        }
        # 其他配置...
    }
}

方法4:针对特定文件类型

location ~* \.(pdf|docx|xlsx)$ {
    # 使用原始文件名作为下载文件名
    add_header Content-Disposition 'attachment; filename="$basename"';
}

注意事项

  1. 文件名中的特殊字符需要转义或使用引号包裹
  2. 中文文件名需要URL编码或使用UTF-8编码
  3. 某些浏览器可能会忽略这个设置,使用自己的命名规则
  4. 确保Nginx有权限访问这些文件

完整示例

server {
    listen 80;
    server_name example.com;

    location /download/ {
        root /var/www;

        # 设置默认下载文件名
        if ($request_filename ~* ^.*?/([^/]*?)$) {
            set $filename $1;
        }

        add_header Content-Disposition 'attachment; filename="$filename"';
    }
}

以上配置可以根据实际需求进行调整,选择最适合你场景的方法。