【问题标题】:How to conditionally set cookie in location section depending on certain query parameter如何根据某些查询参数有条件地在位置部分设置 cookie
【发布时间】:2019-11-13 11:10:46
【问题描述】:

对不同位置的请求可能包含一个查询参数,例如?ide_theme=dark。根据它的存在,我需要在 Nginx 中为参数值设置一个 cookie user_ide_theme。如果请求中没有参数,保留现有的 cookie 很重要。

最直观的方式:

location ~ / {
    # ...

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

    # other locations
}

但它不起作用,Nginx 文档或多或少有明确的解释why if shouldn't be used here

如果在位置上下文中,唯一可以在内部完成的 100% 安全的事情是:

  • 返回...;

  • 重写...最后;

如何根据查询参数有条件地添加此标头?

  • 如果用户已经拥有cookie,则不应清除它,但请求中没有这样的查询参数
  • 如果查询参数中有新内容,则应更新 cookie
  • 请求中不需要保留这个参数

到目前为止,我发现的唯一解决方法是在 if 中使用重定向到相同的地址,但在设置 cookie 后没有查询参数 - 然后它会起作用

【问题讨论】:

    标签: nginx cookies


    【解决方案1】:

    为此使用map 指令:

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

    【讨论】:

    • 谢谢,我试试这个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 2015-06-30
    • 1970-01-01
    • 2021-10-17
    相关资源
    最近更新 更多