【问题标题】:nginx: set cookie in request based on header valuenginx:根据标头值在请求中设置cookie
【发布时间】:2020-02-17 06:33:21
【问题描述】:

我刚刚开始使用 nginx,我正在使用它来代理应用程序服务器。我想将代理 request 中的 cookie 设置到应用程序服务器 if http 请求中存在特定的自定义标头。逻辑是:

if X-SESSID in request
AND SESSID is not already a cookie in the request
    set cookie "SESSID=$http_X-SESSID"

在 apache 2 中,我可以这样做:

RewriteCond %{HTTP:X-SESSID} ^(.*)$
RewriteCond %{HTTP_COOKIE} !SESSID [NC]
RewriteRule (.*) - [E=SESSID:%1]
RequestHeader set Cookie "SESSID=%{SESSID}e" env=SESSID

nginx 中的等效方法是什么?

【问题讨论】:

    标签: nginx


    【解决方案1】:

    你可以这样做:

    # $sessid variable will get a "sessid=$http_x_sessid" value
    # if the X-Sessid HTTP header is set or an empty value otherwise
    map $http_x_sessid $sessid {
        ""       "";
        default  "sessid=$http_x_sessid";
    }
    
    # $sessid_cookie variable will get a value of $sessid variable
    # if no sessid cookie passed with the request or an empty value otherwise
    map $cookie_sessid $sessid_cookie {
        ""       $sessid;
        default  "";
    }
    
    server {
        ...
        # in the same location block where you have a proxy_pass directive
        proxy_set_header Cookie "$http_cookie$sessid_cookie";
        ...
    }
    

    查看maphere$http_... 变量here$cookie_... 变量here 的描述。

    更新@2020.11.12

    查看答案我认为存在缺陷。如果浏览器在传入请求中发送了一些 cookie,则应添加一个带有 ; 前缀的附加 cookie,以便与其他 cookie 分开。这是一个更新的版本:

    # prepend cookie with the "; " if the other cookies exists
    map $http_cookie $prefix_cookie {
        ""       "";
        default  "; ";
    }
    
    # $sessid variable will get a "sessid=$http_x_sessid" value (optionally prepended
    # with "; ") if the X-Sessid HTTP header is set or an empty value otherwise
    map $http_x_sessid $sessid {
        ""       "";
        default  "${prefix_cookie}sessid=${http_x_sessid}";
    }
    
    # $sessid_cookie variable will get a value of $sessid variable
    # if no sessid cookie passed with the request or an empty value otherwise
    map $cookie_sessid $sessid_cookie {
        ""       $sessid;
        default  "";
    }
    
    server {
        ...
        # in the same location block where you have a proxy_pass directive
        proxy_set_header Cookie "$http_cookie$sessid_cookie";
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-21
      • 2021-07-10
      • 2011-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多