nginx:根据标头值在请求中设置Cookie

时间:2020-02-17 06:33:21

标签: nginx

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

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中的等效方法是什么?

1 个答案:

答案 0 :(得分:2)

您可以这样操作:

# $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";
    ...
}

请参见map个块here$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";
    ...
}