Nginx how to multiple if statements

04 Jan 2010

I've been doing a lot of Nginx configuration tweaking recently, due to some complex requirements for a virtual host I'm writing for a relaunch due later this month. As I came across a couple of gotchas and problems that required a lot of head scratching, googling and trawling through the forums, I thought I'd write a series of short posts to try and help any other folk that may have similar Nginx configuration problems in the future.

Multiple if statements

As Nginx doesn't allow multiple or nested if statements you can't do something like:

if ($request_method = POST && $http_cookie ~* "CCCC=.+(?:;|$)")

However, you can set variables and you can do if statements on variables so this can be rewritten:

if ($request_method = POST) {
    set $test  P;

  if ($http_cookie ~* "CCCC=.+(?:;|$)" ) {
    set $test  "${test}C";

  if ($test = PC) {
    #rewrite rule goes here.

As you can use regular expressions on if statements this method allows you to do both && and | checks.

The example is taken from a hidden away example on the wiki but as it took me ages to find hopefully it will help you to.