help with regex in nginx map

Francis Daly francis at
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 {
        location / {
                return 200 "input is :$arg_input:, output is :$my_output_variable:\n";

$ curl
input is ::, output is :it was empty or not set:
$ curl
input is :abc:, output is :is abc:
$ curl
input is :abcc:, output is :matches start abc star end:
$ curl
input is :abcd:, output is :starts with abc:
$ curl
input is :dabcd:, output is :contains abc:
$ curl
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.


Francis Daly        francis at

More information about the nginx mailing list