Nginx conditional not evaluating correctly

Posted by cjc on Server Fault See other posts from Server Fault or by cjc
Published on 2013-06-26T13:01:07Z Indexed on 2013/06/26 22:23 UTC
Read the original article Hit count: 202

Filed under:

I'm running into a weird problem with nginx and how it evaluates conditionals.

Here's the relevant configuration:

set $cors FALSE;
if ($http_origin ~* (http://example.com|http://dev.example.com:8000|http://dev2.example.com)) {
  set $cors TRUE;
}

if ($request_method = 'OPTIONS') {
  set $cors $cors$request_method;
}

if ($cors = 'TRUE') {
  add_header 'Access-Test'    "$cors";
  add_header 'Access-Control-Allow-Origin'    "$http_origin";
  add_header 'Access-Control-Allow-Methods'   'POST, OPTIONS';
  add_header 'Access-Control-Max-Age'         '1728000';
}

if ($cors = 'TRUEOPTIONS') {
  add_header 'Access-Test'    "$cors";
  add_header 'Access-Control-Allow-Origin'    "$http_origin";
  add_header 'Access-Control-Allow-Methods'   'POST, OPTIONS';
  add_header 'Access-Control-Allow-Headers'   'X-Requested-With, X-Prototype-Version';
  add_header 'Access-Control-Max-Age'         '1728000';
  add_header 'Content-Type'                   'text/plain';
}

So, the conditional blocks never trigger.

When I remove the conditions, I see that the "Access-Test" header and the "Access-Control-Allow-Origin" set correctly, but, as noted, enabling the conditionals causes the headers not to be sent.

I'm testing by running:

curl -Iv -i --request "OPTIONS" -H "Origin: http://example.com" http://staging.example.com/

Am I missing something obvious? I've tried the "if" with and without quotes, etc.

This is nginx 1.2.9.

© Server Fault or respective owner

Related posts about nginx