What is map directive in NGINX: Usage and Examples
map directive in NGINX creates variables whose values depend on other variables or request properties. It works like a lookup table, assigning values based on conditions, which helps customize request handling dynamically.How It Works
The map directive in NGINX acts like a simple translator or a decision helper. Imagine you have a list of conditions and for each condition, you want to assign a specific value. The map directive lets you define this list once and then use the assigned values later in your configuration.
For example, you can check the client's IP address, user agent, or request URI and then set a variable to different values based on those checks. This is similar to how you might choose different routes or responses depending on the situation in real life, like choosing a different path based on traffic conditions.
NGINX evaluates the map directive early during request processing, so the mapped variable is ready to use in other directives like proxy_pass, rewrite, or add_header. This makes your configuration flexible and efficient.
Example
This example shows how to use the map directive to set a variable $backend based on the request URI prefix. Requests starting with /api go to one backend, others go to a default backend.
map $request_uri $backend { ~^/api /api_backend; default /default_backend; } server { listen 80; location / { proxy_pass http://$backend; } }
When to Use
Use the map directive when you need to assign values dynamically based on request details without repeating complex conditions. It is perfect for:
- Routing requests to different backends based on URL patterns.
- Setting custom headers or cookies depending on client IP or user agent.
- Enabling or disabling features conditionally.
- Changing behavior without duplicating server blocks.
For example, if you want to serve different content for mobile users or block certain IP ranges, map helps keep your configuration clean and efficient.
Key Points
- map creates variables based on conditions.
- It works like a lookup table for request properties.
- Evaluated early, so variables can be used in many places.
- Helps avoid repeating complex if-else logic.
- Improves configuration clarity and performance.