help with regex in nginx map

Francis Daly francis at daoine.org
Thu Sep 15 22:46:37 UTC 2022


On Thu, Sep 15, 2022 at 01:30:24PM -0400, libresco_27 wrote:

Hi there,

> I'm trying to write a simple regex for a map where only the first part of a
> string should match. I went through the documentation, which unfortunately
> didn't have much examples. 

I'm not sure if you are asking "how to use map", "how to set a variable",
"how to write a regex in nginx", or something else.

Does the following config fragment and example requests help at all?

Within a http{} block:
===
map $arg_input $my_output_variable {
        "" "it was empty or not set";
        default "did not match anything else";
        ~^abc*$ "matches start abc star end";
        ~^abc "starts with abc";
        abc "is abc";
        ~abc "contains abc";
}

server {
        listen 127.0.0.3:80;
        location / {
                return 200 "input is :$arg_input:, output is :$my_output_variable:\n";
        }
}
===

$ curl http://127.0.0.3/
input is ::, output is :it was empty or not set:
$ curl http://127.0.0.3/?input=abc
input is :abc:, output is :is abc:
$ curl http://127.0.0.3/?input=abcc
input is :abcc:, output is :matches start abc star end:
$ curl http://127.0.0.3/?input=abcd
input is :abcd:, output is :starts with abc:
$ curl http://127.0.0.3/?input=dabcd
input is :dabcd:, output is :contains abc:
$ curl http://127.0.0.3/?input=d
input is :d:, output is :did not match anything else:

> map $string $redirct_string{
>      "~^abc*$" 1;
>     }

That regex will only match the strings "ab", "abc", "abcc", "abccc",
etc, with any number of c:s.

> I also tried to change the regex to a simple "abc*", but it didn't work.

That regex will match any string that includes "ab" anywhere in it.

Cheers,

	f
-- 
Francis Daly        francis at daoine.org



More information about the nginx mailing list