问题
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