根据ngx.re.match()添加自定义标头 [英] Adding custom header based on the ngx.re.match()
问题描述
我正在尝试基于uri
值添加自定义标头,在这种情况下,是针对所有pdf
文件:
I'm trying to add custom header based on the uri
value, in this case for all the pdf
files:
header_filter_by_lua_block {
local m, err = ngx.re.match(ngx.var.uri, "%.pdf$", "io")
if m then
ngx.log(ngx.ERR, "found match: ", m[0])
ngx.header["X-Custom-Header"] = "ZZzz"
end
}
我在此任务中使用 lua-nginx-module ,因此我期望标准lua
regex语法应该适用,因此%.
应该与.
(点),但是它似乎不起作用.有什么问题吗?
I'm using lua-nginx-module in this task, therefore I expected that standard lua
regex syntax should apply, thus %.
should match .
(dot), however it doesn't seem to work. What's the problem?
如果我将正则表达式从%.pdf$
更改为.pdf$
,则它确实可以工作,但显然它不仅与blabla.pdf
匹配,而且与blablapdf
匹配.
If I change regex from %.pdf$
to .pdf$
then it does work, but obviously it matches not just blabla.pdf
but also blablapdf
.
推荐答案
lua-nginx-module使用PCRE(与Perl兼容的正则表达式),因此应使用\
而不是%
来转义特殊字符.反斜杠也是Lua字符串转义符号,因此需要两次转义:
lua-nginx-module uses PCRE (Perl compatible regular expression), so \
should be used instead of %
to escape special characters. Backslash is also Lua string escape symbol, so double escape is needed:
ngx.re.match(ngx.var.uri, "\\.pdf$", "io")
或者,您可以使用方括号字符串文字而不是引号来避免双重转义:
Alternatively, you can use bracket string literals instead of quotes to avoid double escape:
ngx.re.match(ngx.var.uri, [[\.pdf$]], "io")
这篇关于根据ngx.re.match()添加自定义标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!