captcha

The captcha directive enables the generation and handling of CAPTCHA images in NGINX.

Syntaxcaptcha;
Defaultnone
Contextlocation
Argumentsnone

Description

The captcha directive is part of the NGINX Captcha Module, which provides functionality for generating CAPTCHA images to protect against automated requests. When the captcha directive is enabled within a location block, NGINX will create a CAPTCHA challenge that consists of a randomly generated string composed of characters defined by the captcha_charset directive. The generated CAPTCHA is then hashed together with a CSRF token to create a secure cookie, which is sent to the client for validation. This mechanism helps ensure that only legitimate requests are processed, adding a layer of security to web applications.

When processing a request at the specified location, NGINX first checks the request method; it only allows GET or HEAD requests. Upon validation, it generates a random string based on the specified length and character set. If the captcha_case directive is set to on, the comparison of the CAPTCHA input will be case-insensitive. Afterward, NGINX computes an MD5 hash involving the CAPTCHA text, a secret key, and the CSRF token to provide an additional layer of security. If the generated hash matches the value provided by the client in a cookie, the CAPTCHA is considered valid.

Config Example

location =/captcha {
    captcha;
}
location =/login {
    set_form_input $csrf_form csrf;
    set_unescape_uri $csrf_unescape $csrf_form;
    set_form_input $captcha_form captcha;
    set_unescape_uri $captcha_unescape $captcha_form;
    set_md5 $captcha_md5 "secret${captcha_unescape}${csrf_unescape}";
    if ($captcha_md5 != $cookie_captcha) {
        # captcha invalid code
    }
}

Ensure the CSRF token is properly configured, as failure to do so can lead to captcha validation issues.

Cookies need to be enabled in the client for proper functioning of captcha validation.

Overlapping configuration settings for other directives in the same location can affect captcha behavior.

← Back to all directives