Nginx can struggle with rules which require multiple conditions to be checked. This guide will show how to set up multiple-condition EdgeRules.
The EdgeRules feature is available only on Enterprise plans.
Example Condition
An example requirement might be to redirect visitors from http://domain.com/ to http://domain.com/test/uri:
- if Nginx captures /test/uri AND
- the request header
Accept
is defined with value "test" AND - there is a query string "debug=1"
The simplest solution with any programming language is to combine conditions within a single “if” statement (i.e. if something = 1 and something else = 2). However, this can’t be done with Nginx and therefore can’t be done with MaxCDN’s EdgeRules. Instead, we will use variables with multiple “if” statements to define different states for variables that can be used in the final action. In the example below, the final action is redirection.
EdgeRules Configuration
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;
}
What we are doing here is a bit of a hack, 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
The “if” statement in Nginx can be 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 unpredictable.
If you have any questions about handling multiple conditions with local Nginx variables, please feel free to reach out to support. Live chat and ticket support are available 24/7.