在Nginx中,你可以通过配置Content-Disposition
响应头来指定文件下载时的默认保存文件名。以下是几种实现方式:
add_header
指令location /download/ {
# 设置Content-Disposition头指定文件名
add_header Content-Disposition 'attachment; filename="your-filename.ext"';
# 其他配置...
}
$args
或变量动态指定文件名location /download/ {
# 从URL参数中获取文件名
if ($args ~* "filename=([^&]+)") {
set $downname $1;
add_header Content-Disposition 'attachment; filename="$downname"';
}
# 其他配置...
}
map
指令映射文件名map $uri $downname {
~/download/(.*) $1;
default "";
}
server {
location /download/ {
if ($downname) {
add_header Content-Disposition 'attachment; filename="$downname"';
}
# 其他配置...
}
}
location ~* \.(pdf|docx|xlsx)$ {
# 使用原始文件名作为下载文件名
add_header Content-Disposition 'attachment; filename="$basename"';
}
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"';
}
}
以上配置可以根据实际需求进行调整,选择最适合你场景的方法。