Franz`s blog

Nginx 中使用中文路径使用 try_files 的一些坑

nginx 配置如下

1
2
3
4
5
6
7
8
9
location ~ /download/(?<filename>.*) {
set $bid "";
set $filename $1;
access_by_lua_file lua/auth.lua;
root /toss/;
try_files /$bid/$filename /$filename =404;
lua_code_cache off;
charset utf-8;
}

当通过 http://example.com/download/测试.jpg 时出现404 no found问题

原因是filename变量是通过urlencode后的值,nginx在磁盘中找不到该文件

解决方法: 通过access_by_lua_file解码并修改更改filename的值

核心代码如下:

1
2
3
4
5
local function urlDecode(s)
s = string.gsub(s, '%%(%x%x)', function(h) return string.char(tonumber(h, 16)) end)
return s
end
ngx.var.filename = urlDecode(ngx.var.filename)

如果解码之后还是出现404 no found可以使用locale检查一下服务器编码确定是utf-8编码,即LANG=en_US.utf8 并且在location块配置charset utf-8;