if

The 'if' directive allows conditional processing of requests based on specified criteria.

Syntaxif (condition) { ... }
Defaultnone
Contextserver, location
Argumentsblock (1+)

Description

The 'if' directive in NGINX is a powerful control structure that enables conditional configuration by executing a block of configuration directives based on the evaluation of specified conditions. It can be used in both the server and location contexts, which makes it versatile for controlling access or behavior for specific resources or paths. The syntax uses a Boolean expression to check conditions, and if the expression evaluates to true, the directives within the block will be executed. The conditions include a variety of request parameters, such as headers, request methods, and client IP addresses.

When using the 'if' directive, it is important to ensure that the condition is correctly formed, as improper configurations can lead to unexpected behaviors. The directive can take a sequence of nested or sequential 'if' blocks, which can further complicate logic flow. Each 'if' block can contain multiple directives that will be executed when the condition holds true. However, caution must be exercised with the 'if' directive, especially regarding its interaction with other directives, as misuse can lead to configuration issues or inefficiencies. A common use case involves denying access to certain IP ranges or redirecting requests based on headers or other criteria.

Config Example

if ($http_user_agent ~ MSIE) {
    return 403;
}

if ($remote_addr = 192.168.1.1) {
    access deny;
}

Nested 'if' statements can lead to unexpected behavior and should be used with caution.

Using 'if' in a location context can have unintended effects on request processing.

Conditions based on variables should be carefully evaluated to avoid always true/ false outcomes.

← Back to all directives