Adding custom header based on the ngx.re.match()

2020-05-05 00:43发布

问题:

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
  }

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?

If I change regex from %.pdf$ to .pdf$ then it does work, but obviously it matches not just blabla.pdf but also blablapdf.

回答1:

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")


标签: regex nginx lua