3

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?

cnst
  • 25,870
  • 6
  • 90
  • 122
Alireza
  • 6,497
  • 13
  • 59
  • 132
  • @Dayo, your edit has resulted in pertinent information being removed from the question. after your edit, it was no longer clear what the OP wanted to have had accomplished. – cnst Jul 01 '16 at 22:59

1 Answers1

5

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;
cnst
  • 25,870
  • 6
  • 90
  • 122
  • I've got `{"reason": "There was no x-client-id and could not extract client_id from Authorization header."}` – Alireza Jul 02 '16 at 11:52
  • It seems that when header for `x-client-id` is not set, the first line raise error and return 400 to user – Alireza Jul 02 '16 at 11:53
  • @AlirezaHos, I have no idea why you're getting it, it certainly doesn't come from nginx. After your report, I've actually tried the very exact configuration above, and it works as expected. If you want to have a default value, when neither one of the above options is set, just add an extra if-statement (just make sure they're sequential, and not nested). – cnst Jul 02 '16 at 14:59
  • @AlirezaHos, so, this should really be working! If you're still having some issues, feel free to add more information if you want further help. – cnst Jul 03 '16 at 19:32
  • Thanks it worked as expected. I don't know what was the issue past then. Today I tested on a different machine and it worked. – Alireza Jul 04 '16 at 10:52
  • @AlirezaHos, great, thanks for the bounty and accept! Since it all worked 100%, can I get a +1, please? :-) (The [tag ratings](http://stackoverflow.com/tags/ngx-http-rewrite-module/topusers) apparently don't take accepts or bounties into account.) P.S. I already gave you a +1 back 2 days ago. – cnst Jul 04 '16 at 15:00
  • Thank you for the help, sure. +1 – Alireza Jul 05 '16 at 05:47