Dump the code

Map directive

Created 7 months ago
Posted By admin
2min read
"map" is a directive that allows you to create key-value mappings. It's commonly used to transform or map values, which can be helpful in various scenarios, such as rewriting URLs, setting variables based on conditions, or dynamically configuring other directives.

Here's a basic syntax of the map directive:

map $variable $new_variable {
    value1 mapped_value1;
    value2 mapped_value2;
    default default_value;
}
  • map: This is the keyword indicating the start of the map block.
  • $variable: The variable whose value you want to map.
  • $new_variable: The variable that will store the mapped value.
  • value1, value2: Possible values of the original variable.
  • mapped_value1, mapped_value2: The corresponding values to map to.
  • default: An optional keyword specifying the default value if no match is found.
  • default_value: The value to use when no match is found.

Here's an example that demonstrates how you might use the map directive to rewrite URLs:

map $uri $new_uri {
    /old-path/ /new-path/;
    /another-old-path/ /another-new-path/;
    default $uri;
}

server {
    location / {
        rewrite ^ $new_uri permanent;
    }
}
In this example, the map directive is used to create a mapping between old paths and their corresponding new paths. The rewrite directive then uses the mapped value to redirect the request to the new path.

Keep in mind that the map block should be placed in the http block of your Nginx configuration file, and you can use the mapped variable ($new_uri in the example) elsewhere in your configuration file. This allows for dynamic configuration based on various conditions and simplifies the management of mappings.
Topics

Mastering Nginx

27 articles

Bash script

2 articles

Crontab

2 articles