Oleh Rybalchenko
Oleh Rybalchenko

Reputation: 8059

How to conditionally set cookie in location section depending on certain query parameter

Requests to various locations may contain a query parameter like ?ide_theme=dark. Depending on its presence, I need to set a cookie user_ide_theme to the parameter value in Nginx. It's important to keep existing cookie if the parameter is absent in request.

The most intuitive way:

location ~ / {
    # ...

    if ($arg_ide_theme) {
        add_header Set-Cookie 'user_ide_theme=$arg_ide_theme;Path=/;HttpOnly';
    }

    # other locations
}

But it doesn't work and Nginx docs have more or less clear explanation why if shouldn't be used here.

The only 100% safe things which may be done inside if in a location context are:

  • return ...;

  • rewrite ... last;

How can I add this header conditionally depending on a query parameter?

The only workaround I found so far is to use redirect inside if to the same address, but without query parameter after setting a cookie - then it would work

Upvotes: 0

Views: 1364

Answers (1)

Ivan Shatsky
Ivan Shatsky

Reputation: 15547

Use map directive for this:

map $arg_ide_theme $user_ide_theme {
    "~^(.+)$" "user_ide_theme=$1;Path=/;HttpOnly";
    default "";
}

server {
    ...
    add_header Set-Cookie $user_ide_theme;
    ...
}

Upvotes: 2

Related Questions