Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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"

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.

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

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.