Important note

The EdgeRules feature is available only on Enterprise plans.

One common problem with Nginx rules is the multiple condition requirement in which different parameters are in question.

For example, let’s say you have a requirement to redirect visitors to http://domain.com/ with a uri that was captured Nginx side. If Nginx catches /test/uri, the redirection should direct to http://domain.com/test/uri – but ONLY if the request header Accept is defined with value “test” and there is a query string “debug=1”.

The everyday solution with any programming language is to have double “if” conditions within a single “if” statement [ex: if (something = 1 and somethingelse = 2)]. But this can’t be done with Nginx and therefore can’t be done with MaxCDN’s EdgeRules. Not this way anyhow.

What you can do instead is use variables with multiple “if” statements to define different states for variables that you can use in the final action. In the example below, the final action is redirection. Let’s take a look…

Nginx Configuration Block

set $tmp 0;
if ($http_accept = test) {                                  
	set $tmp 1;
}
if ($args = debug=1) {                                  
	set $tmp "${tmp}1";
}
if ($tmp = 11) {                                  
	rewrite ^ http://domain.com/$uri permanent;
}

So we’re doing a sort of a hack here where we define variable “tmp” with value “0”. We then set the first condition of the same variable to “1” and the request header Accept to the value “test”. Since we have two conditions, we’re appending “1” to whatever the value was of “tmp” (with “${tmp}1”) variable and finally checking if the “tmp” variable contains the expected “11” value. If yes, we’re putting the rewrite directive into place.

cURL Examples

Default example request that meets none of the conditions:

$ curl -I cdn.domain.com/
HTTP/1.1 200 OK


New request with only query string defined:

$ curl -I cdn.domain.com/?debug=1
HTTP/1.1 200 OK

Another request with only request Accept header defined:

$ curl -I cdn.domain.com/ -H 'Accept: test'
HTTP/1.1 200 OK

Finally, request with both expected parameters satisfied:

$ curl -I cdn.domain.com/?debug=1 -H 'Accept: test'
HTTP/1.1 301 Moved Permanently
Location: http://domain.com//?debug=1
NOTE: The “if” statement in Nginx can be considered “dangerous” if it’s improperly used within the location block (within location context). IF is a part of the rewrite module and, as such, it’s only ever 100% safe with rewrite and return directives. In other cases it can be… well, unpredictable.

Reference: https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/

If you have any questions about handling multiple conditions with local Nginx variables, please leave a comment below or start a live chat.