How to conditionally override a header in nginx only if a cookie exist?

五迷三道 提交于 2019-12-10 18:44:56

问题


Is there a way to check if a specific cookie exist in nginx?

For now I have a section like below to set header from cookie:

proxy_set_header x-client-id $cookie_header_x_client_id;

I want to check if that cookie exist then set the header, otherwise do not override header.

I've tried:

if ($cookie_header_x_client_id) {
    proxy_set_header x-client-id $cookie_header_x_client_id;
}

But it does not work and gives the error below:

"proxy_set_header" directive is not allowed here in /etc/nginx/sites-enabled/website:45

Any solution?


回答1:


There are only a limited number of directives that are allowed within an if context in nginx. This is related to the fact that if is part of the rewrite module; as such, within its context, you can only use the directives that are specifically outlined within the documentation of the module.

The common way around this "limitation" is to build up state using intermediate variables, and then use directives like proxy_set_header using such intermediate variables:

set $xci $http_x_client_id;
if ($cookie_header_x_client_id) {
    set $xci $cookie_header_x_client_id;
}
proxy_set_header x-client-id $xci;


来源:https://stackoverflow.com/questions/38038689/how-to-conditionally-override-a-header-in-nginx-only-if-a-cookie-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!