nginx

nginx how to check the value of optional header


how do check for the value of a optional header in nginx? I was thinking of using a map function,

map $http_optional_header $is_header_valid {
    default 0;
    "true" 1;
    "Y" 1;
    "false" 1;
    "N" 1;
}
if ($is_header_valid = 0){
   return 400 }

however, in the default case if header is missing the checks fails, making the header mandatory, but if I make default value as 1, any value would be valid, how do I check the header in nginx so that if the header is not present, we will use header value as false, but if the header is present, the value has to be one of the above else we throw an error?


Solution

  • Further to your comment:

    map $http_optional_header $is_header_valid { default 0; "true" 1; "Y" 1; "false" 1; "N" 1; "" 1; } ok yeah, I suppose that will work, and then I will add another check to set header as false if header is empty if ($http_optional_header = ""){
    set $http_optional_header "false"; }

    $http_optional_header is a built in variable and may or may not be set-able. You will need to test this.

    I am not sure how you use $http_optional_header within the rest of your configuration, but an alternative method uses a slightly different map and a single if.

    For example:

    map $http_optional_header $header_value {
        "true"  $http_optional_header;
        "Y"     $http_optional_header;
        "false" $http_optional_header;
        "N"     $http_optional_header;
        ""      "false";
    }
    if ($header_value = "") { return 400; }
    

    By default, $header_value is an empty string if none of the above match.

    Within the rest of your configuration use $header_value instead of $http_optional_header.