set_random

The `set_random` directive generates a random string based on specified parameters.

Syntaxset_random variable [length] [charset];
Defaultnone
Contexthttp, server, location, if in server, if in location
Arguments3

Description

The set_random directive is part of the NGINX Set-Misc module and allows users to generate random strings directly within their configuration files. This directive can take up to three arguments: the variable to set, an optional length for the random string, and an optional character set from which to draw characters for the string. When used, it replaces the specified variable with a randomly generated value based on the provided length and character set or falls back to default behavior if these are omitted.

By default, if the length is not specified, the set_random directive generates a random string of 16 characters. If no character set is specified, it defaults to using alphanumeric characters (both uppercase and lowercase letters, as well as digits). This makes set_random a versatile directive for various use cases, such as creating tokens, passwords, or unique identifiers for session management or caching purposes. It's also important to note that this directive requires a proper context, and it can be used in http, server, location, or if blocks, depending on the desired scope.

Config Example

location /generate-token {
    set_random $token 32 'a-zA-Z0-9';
    add_header X-Generated-Token $token;
}

Ensure that the specified length does not exceed the limits of internal variable storage.

Using a custom character set requires correct formatting to ensure valid characters are specified.

← Back to all directives