Categories
Linux

Nginx IF for multiple conditions

Nginx works smooth, really fast and in the config files you can write basic conditions using IF statements. Issue: You can not concatenate.

I found at this gist a smart hack to accomplish this and work very well:

    if ($request_uri = /) { 
      set $test  A; 
    } 
  
    if ($host ~* teambox.com) { 
      set $test  "${test}B"; 
    } 
  
    if ($http_cookie !~* "auth_token") { 
      set $test  "${test}C"; 
    } 
    
    if ($test = ABC) { 
      proxy_pass http://teambox-cms.heroku.com; 
      break; 
    } 

In my case I wanted only to force a redirect for the home page of our domain, but the rest of the domain/pages optional to choose between HTTP or HTTPS.

So I ended up having this:

## we only force the HTTPS to the home page but we allow to browse without HTTPS if they want to.
    if ($request_uri = /) { 
      set $test  A; 
    } 
    if ($scheme = 'http') { 
      set $test  "${test}B"; 
    } 
    if ($test = AB) { 
        rewrite  ^/(.*)$  https://domain.com/$1  permanent;
    } 
    ## END if Hack