Multiple if Conditions in Nginx

It it amazing that Nginx server configuration does NOT support multiple conditions natively. Like this.

if ($request_method = 'GET' && $arg_user){}

Which means if did not support AND and OR operations in common programming language.

Nginx doesn’t allow multiple if statements in the nested form also.

Like this.

if ($request_method = 'GET'){
    if ($arg_user){

According to nginx Wiki “if is evil” (yes, this is how it is phrased in Wiki).

  • “Directive if has problems when used in location context, in some cases it doesn’t do what you expect but something completely different instead. In some cases it even segfaults. It’s generally a good idea to avoid it if possible.”
  • It is frequently misunderstood, and misused. In short: it is not if of C.
  • Performance problem: server-level if is evaluated for every request, even when non-images are requested. The same is true for unrestricted location-level if directives.

There is a Hack for the problem

When there’s a will there’s a way.

Setting a variable in each tested-true condition and when the variable reflects that both conditions are true, do what you need to do.

Like this.

   set $UD "";
   if ($arg_user){
      set $UD T;
   if ($request_method = 'GET'){
      set $UD "${UD}G";
   if ($UD = TG){

In this UD is a variable initialise empty. Then when the first if condition is true ‘T’ is added to it.

similarly when second condition is true I concatenate ‘G’ to it.

This way UD only have ‘TG’ in it if both above conditions are true.

Problem solved…


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s