Skip to content
arut edited this page Jan 11, 2012 · 7 revisions

Arithmetic operations in NGINX config

nginx-let-module adds support of arithmetic operations to NGINX.

"let" directive

"let" directive evaluates expression and assigns it to a variable. It has the following syntax:

let $var EXPRESSION;

For example:

let $a 1 + 2;

In this example variable $a is simply assigned the value of 3. More complicated expressions are supported which include parentheses and references to other variables

let $a 100 & 0x7f;
let $b $a + 50;
let $c ( ( $a + $b ) / 3 + 199 ) % 37;

String concatenation:

let $s "Hi " . $user . ". You have " . $nmsg . " messages ";

Function calls:

let $h substr( sha1( $username ) 0 4 );
let $ss substr( $mystring 1 2 );
let $rr rand() % 33;
let $slen length( $datastring );

Operands

Operands can be literals or variables (start with '$'). In numeric operations hexadecimal integers are recognized:

let $a 0x123;

Operation list

  • integer + - * /
  • remainder %
  • bitwise & |
  • string concatenation '.'

Operations can be grouped with parentheses and nested. Usual operation precedence rules are used.

Functions

numeric

  • rand()
  • max( x y )
  • min( x y )

string

  • length( s )
  • substr( s offset length )

cryptographic

  • md4( x )
  • md5( x )
  • sha1( x )
  • sha224( x )
  • sha256( x )
  • sha384( x )
  • sha512( x )
  • ripemd160( x )

Notes

This module uses NGINX config parser as lexer. It leads to the fact that all tokens should be separated with spaces when using "let" directive.

let $a (1+2);        # ERROR NO SPACES!
let $a ( 1 + 2 );    # OK

let $a length($s);   # ERROR NO SPACES!
let $a length( $s ); # OK

In the last example opening parenthesis is a part of function name and should not be separated from it.

For functions with no arguments an exception is made and the following syntax is permitted:

let $r rand();