Nginx:在重写中转义非字母数字字符
Nginx: escape non-alphanumeric characters in rewrite
我正在从 Apache 迁移到 Nginx,我需要一种方法来转换 Apache 的重写标志 [B]。
[B] 标志在应用重写转换之前转义所有非字母数字字符。
例如
x & y/z
将转换为
x%20%26%20y%2Fz
有没有办法在 Nginx 中做到这一点?我在网上找到的示例只删除了这些字符,但我需要一种方法来转换它们。
如有任何信息,我们将不胜感激。
谢谢
Nginx 为此提供了一些默认功能。
您可以使用 ngx.escape_uri
和 ngx.unescape_uri
或 ngx.encode_args
和 ngx.decode_args
以及一些 lua 来编码解码。 Here are docs
如果您需要自定义解决方案,可以为该任务自定义代码 lua 模块,或者像这样 lua module 来转换特殊字符
步骤是:
- 安装 lua-rocks 和 html-entities 库
apt-get install luarocks
luarocks install html-entities
- html-entites 库会将每个字符转换为 html 实体。所以你应该过滤你需要的字符。在这个例子中,我正在转换所有不是基本英文字母的字符。创建文件 mymodule.lua
htmlEntities = require('htmlEntities')
local mymodule = {}
function mymodule.convert(string)
return string:gsub("[^a-zA-Z]", function(c) return htmlEntities.encode(c) end)
end
return mymodule
- 在nginx.conf
指定 lua 路径。这将加载 path2 文件夹
中的所有 lua 个文件
http {
lua_package_path "/path1/path2/?.lua;;";
...
要使用该模块,您可以使用 *_by_lua 指令。例如在位置
set_by_lua $escape "return require('mymodule').convert(ngx.var.name);" $name;
我正在从 Apache 迁移到 Nginx,我需要一种方法来转换 Apache 的重写标志 [B]。
[B] 标志在应用重写转换之前转义所有非字母数字字符。 例如
x & y/z
将转换为
x%20%26%20y%2Fz
有没有办法在 Nginx 中做到这一点?我在网上找到的示例只删除了这些字符,但我需要一种方法来转换它们。
如有任何信息,我们将不胜感激。
谢谢
Nginx 为此提供了一些默认功能。
您可以使用 ngx.escape_uri
和 ngx.unescape_uri
或 ngx.encode_args
和 ngx.decode_args
以及一些 lua 来编码解码。 Here are docs
如果您需要自定义解决方案,可以为该任务自定义代码 lua 模块,或者像这样 lua module 来转换特殊字符
步骤是:
- 安装 lua-rocks 和 html-entities 库
apt-get install luarocks
luarocks install html-entities
- html-entites 库会将每个字符转换为 html 实体。所以你应该过滤你需要的字符。在这个例子中,我正在转换所有不是基本英文字母的字符。创建文件 mymodule.lua
htmlEntities = require('htmlEntities')
local mymodule = {}
function mymodule.convert(string)
return string:gsub("[^a-zA-Z]", function(c) return htmlEntities.encode(c) end)
end
return mymodule
- 在nginx.conf 指定 lua 路径。这将加载 path2 文件夹 中的所有 lua 个文件
http {
lua_package_path "/path1/path2/?.lua;;";
...
要使用该模块,您可以使用 *_by_lua 指令。例如在位置
set_by_lua $escape "return require('mymodule').convert(ngx.var.name);" $name;