【问题标题】:Adding custom header based on the ngx.re.match()基于 ngx.re.match() 添加自定义标头
【发布时间】:2019-01-18 06:42:19
【问题描述】:

我正在尝试添加基于 uri 值的自定义标头,在这种情况下适用于所有 pdf 文件:

  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 syntax 应该适用,因此%. 应该匹配.(点),但它似乎不起作用。有什么问题?

如果我将正则表达式从%.pdf$ 更改为.pdf$,那么它确实有效,但显然它不仅匹配blabla.pdf,还匹配blablapdf

【问题讨论】:

    标签: regex nginx lua


    【解决方案1】:

    lua-nginx-module 使用 PCRE(Perl 兼容的正则表达式),所以应该使用 \ 而不是 % 来转义特殊字符。反斜杠也是 Lua 字符串转义符号,所以需要 双转义

    ngx.re.match(ngx.var.uri, "\\.pdf$", "io")
    

    或者,您可以使用括号字符串文字而不是引号来避免双重转义:

    ngx.re.match(ngx.var.uri, [[\.pdf$]], "io")
    

    【讨论】:

      猜你喜欢
      • 2012-05-17
      • 1970-01-01
      • 2013-11-13
      • 1970-01-01
      • 2020-12-16
      • 2016-10-18
      • 2013-05-15
      • 2012-04-08
      相关资源
      最近更新 更多