Skip to content

Instantly share code, notes, and snippets.

@mylxsw
Last active December 26, 2023 02:37
Show Gist options
  • Save mylxsw/c4c63d40489595239bd60062de5687c8 to your computer and use it in GitHub Desktop.
Save mylxsw/c4c63d40489595239bd60062de5687c8 to your computer and use it in GitHub Desktop.
nginx+lua解决不同浏览器文件下载兼容性,解决文件乱码问题
location /download/ {
root /home/data/images;
if ($request_uri ~* ^.*\/(.*)\.(doc|txt|zip|jpg|jpeg|png|gif|pdf|rar|xls|xlsx|docx|ppt|pptx|wps)(\?name=([^&]+))$) {
set $filename "$arg_name.$2";
header_filter_by_lua_block {
if ngx.status ~= 200 then
return
end
local ua = ngx.req.get_headers()["User-Agent"]
if type(ua) ~= "string" then
ua = ua[1]
end
local filename = ngx.var.filename
if string.match(ua, "MSIE") ~= nil then
filename = ngx.escape_uri(filename)
ngx.header["Content-Disposition"] = "attachment;filename=\"" .. filename .. "\""
elseif string.match(ua, "Firefox") ~= nil then
filename = "utf8'zh_cn'" .. filename
ngx.header["Content-Disposition"] = "attachment;filename*=\"" .. filename .. "\""
else
ngx.header["Content-Disposition"] = "attachment;filename=\"" .. filename .. "\""
end
}
}
}
@nilyang
Copy link

nilyang commented Jun 2, 2017

Nice!

@fddc
Copy link

fddc commented Dec 26, 2023

有用,感谢

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment