January 25, 2013

Nginx Multiple If Statements

Nginx doesn’t allow multiple if statements, so if you need to match multiple rules and you’re not checking if files exist then this is how you need to proceed.

set $posting 0; # Make sure to declare it first to stop any warnings
 
if ($request_method = POST) { # Check if request method is POST
  set $posting N; # Initially set the $posting variable as N
}
 
if ($geoip_country_code ~ (BR|CN|KR|RU|UA) ) { # Here we're using the Nginx GeoIP module to block some spammy countries
  set $posting "${posting}O"; # Set the $posting variable to itself plus the letter O
}
 
if ($posting = NO) { # We're looking if both of the above rules are set to spell NO
  return 403; # If it is then let's block them!
}

As you can see we have to use a variable, adding another character at each step and matching the final value with what we want to do.

Leave a Reply

Your email address will not be published. Required fields are marked *

css.php