如何在Lua中对request_uri字符串进行urldecode

当我使用 ngx.var.request_uri 时,返回的字符串中包含 %20 而非空格。是否有 urldecode() 或类似的函数来解码我的字符串?

原文链接 https://stackoverflow.com/questions/20282054

点赞
stackoverflow用户204011
stackoverflow用户204011

解码后的 URI 可在 ngx.var.uri 中找到。如果需要查询字符串,请参阅 ngx.var.query_string

EDIT:如果您无法使用它,这里有一种在 Lua 中取消转义 URL 的简单方法。

local hex_to_char = function(x)
  return string.char(tonumber(x, 16))
end

local unescape = function(url)
  return url:gsub("%%(%x%x)", hex_to_char)
end

示例用法:

local url = "/test/some%20string?foo=bar"
print(unescape(url)) -- /test/some string?foo=bar

但是,在使用它之前,您应该将查询字符串分割。

2013-11-29 09:59:42
stackoverflow用户1850358
stackoverflow用户1850358

如果您正在使用nginx-lua-module,那么可以使用以下API来进行操作。

newstr = ngx.unescape_uri(str)

您还可以查看ngxescape_uri

2013-12-06 13:55:37
stackoverflow用户4935114
stackoverflow用户4935114

LuaSocket提供了url.unescape工具。引用说明如下:

url.unescape(content)

从字符串中移除URL转义内容编码。

Content是要解码的字符串。

函数返回解码后的字符串。

2019-02-14 15:41:47
stackoverflow用户5911601
stackoverflow用户5911601

尝试使用 nginx-lua-module 中的 ngx.req api。

  • ngx.req.set_uri: 重写 uri,仅重写路径。如果您还想替换参数,请使用 ngx.req.set_uri_args
  • ngx.escape_uri:用于编码字符串
  • ngx.unescape_uri:用于解码字符串

例如:解码路径和参数

location / {
  .....

  rewrite_by_lua_block {
       # 获取nginx变量$uri,无法更改为$request_uri,$args...
       local uri = ngx.var.uri

       # 使用以下api解码参数
       ngx.req.set_uri_args(ngx.unescape_uri(ngx.var.args));

       # 使用set_uri解码路径
       ngx.req.set_uri(ngx.unescape_uri(uri));
  }
}
proxy_pass ....;

参考文献:https://github.com/openresty/lua-nginx-module#ngxreqset_uri

2020-03-10 10:29:17