Use Nginx’s map directive to derive a variable from a request or connection value, then use that variable in another directive. Put an HTTP map inside http {} (or an included file loaded there), define an explicit default, and remember that exact keys beat wildcard masks, wildcard masks beat regular expressions, and regular expressions are tested in the order written.
Need a server to try this on? Antihost offers Linux VPS plans with NVMe storage, full root access and a 14-day free trial.
What the Nginx map module does
The official description of ngx_http_map_module is precise: it creates variables whose values depend on values of other variables. A map is therefore a lookup-and-transform declaration, not an action by itself. The block defines a derived variable; another directive must consume that variable.
As an Amazon Associate I earn from qualifying purchases.
The general syntax is:
map string $variable {
key value;
default fallback;
}
The first argument is the source expression. It can contain one variable or a combination of variables. The second argument is the name of the result variable. Each line in the block maps an input key to an output value.
Map results are evaluated when the result variable is used. Declaring even a large map does not, by itself, add request-processing work. This lazy evaluation makes maps useful for optional headers, routing decisions, feature flags, cache keys and access policies that are needed only on selected requests.
#1 Best Overall
- [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
- [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
- [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
- [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
- [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.
Where a map block belongs
An HTTP map belongs directly inside the top-level http context. It cannot be declared inside a server or location block.
http {
map $http_host $site_class {
default other;
example.com primary;
*.example.com subdomain;
}
server {
listen 80;
server_name example.com *.example.com;
add_header X-Site-Class $site_class always;
}
}
If you keep configuration in separate files, include the file from the http context:
Recommended Free Tools
http {
include conf.d/maps/*.conf;
server {
listen 80;
}
}
The map’s result variable is available to directives that run in a request context, provided those directives support variables. A map declaration that is never referenced has no visible effect.
A first working map
Map a host name to a label
This example classifies requests by the value of the HTTP Host header:
map $host $site_class {
default other;
example.com primary;
*.example.com subdomain;
}
server {
listen 80;
server_name example.com *.example.com;
add_header X-Site-Class $site_class always;
}
$host is the normalized host value Nginx selected for the request. The map produces primary, subdomain or other, and the add_header directive exposes that result for inspection. In production, the consuming directive might instead select a cache policy, set a response header, choose a log format or pass a value to an application.
Test the configuration safely
- Save the map in the file included by the
httpblock, or add it directly insidehttp {}. - Run
nginx -twith the same configuration path used by the service. The command must report a successful syntax test before a reload. - Reload Nginx using your service manager, for example
systemctl reload nginx, after the test succeeds. - Send requests with representative host values and inspect the response header or other directive that consumes the mapped variable.
Testing both a matching and an unmatched value is important: an omitted fallback produces an empty result.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Rank #2
- 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
- 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
- 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
- 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
- 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
How Nginx chooses a matching entry
When more than one entry could match, Nginx uses a fixed precedence order. Understanding it prevents a broad wildcard or an early regular expression from overriding a more specific policy.
- Exact string without a mask. Literal keys are checked first and are matched without regard to case.
- Longest prefix mask. A mask such as
*.example.commatches the beginning of a host name; if several prefix masks match, the longest one wins. - Longest suffix mask. A mask such as
mail.*matches the ending portion; the longest matching suffix wins. - First regular expression. Regex keys begin with
~for case-sensitive matching or~*for case-insensitive matching. They are evaluated in the order written, and the first match wins. - Default. If no prior entry matches, Nginx uses
default. If no default is declared, the result is an empty string.
For example:
map $host $tier {
default unknown;
example.com exact;
*.example.com wildcard;
~^api[0-9]+. api-numbered;
}
A request for example.com receives exact, even though a broader rule might also apply. A matching regular expression cannot override an exact key or a matching mask. Among regexes, moving a line higher or lower changes the result, so order is part of the policy.
Hostname masks and the hostnames; parameter
Use hostnames; when the map should interpret prefix and suffix masks as hostname patterns. It must appear before the value entries:
map $host $allowed_host {
hostnames;
default 0;
example.com 1;
*.example.com 1;
}
This allows the exact host and its subdomains to be listed explicitly. Nginx also supports combining them into the shorter .example.com form:
map $host $allowed_host {
hostnames;
default 0;
.example.com 1;
}
The result is a string, so values such as 1 and 0 are commonly passed to an access-related directive or tested in a conditional. A map is not a substitute for validating the Host header at the server-selection layer: define appropriate server_name values and reject unwanted hosts separately when that is part of your threat model.
Regular expressions and captures
Regex entries start with ~ or ~*. A map regex can expose named or positional captures in its result. Named captures become ordinary Nginx variables that can be used later in configuration.
Rank #3
- [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
- [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
- [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
- [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
- [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by
map $uri $image_ext {
default "";
~^/images/.+.(?<ext>jpg|png)$ $ext;
}
server {
listen 80;
add_header X-Image-Extension $image_ext always;
}
Here, a URI such as /images/logo.png produces png. The capture name ext is clearer and more stable than relying on a positional capture.
Positional captures are available as $1 through $9, but they share the request or connection capture set. Another regex evaluated later can replace those positions. If a captured value must be referenced by several later directives, prefer a named capture and verify the syntax against the PCRE support in the installed Nginx build.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Regexes are powerful but less transparent than literal and mask entries. Keep them narrow, document what they accept, and place more specific expressions before broad ones.
Map request headers, methods and combined inputs
Map a header to a policy value
map $http_x_tenant $backend_class {
default unknown;
tenant-a standard;
tenant-b priority;
}
server {
listen 80;
add_header X-Backend-Class $backend_class always;
}
HTTP request headers are exposed as variables with the $http_ prefix followed by a lower-case header name. Decide what should happen when the header is absent or untrusted; the default entry is the place to make that decision explicit.
Combine several variables
Use a composite source when the result depends on more than one input:
map "$request_method:$uri" $cache_mode {
default bypass;
GET:/assets/ cache;
~^GET:/products/ short-cache;
}
Composite expressions are useful for method-and-path policies, protocol-and-host routing, or a small state matrix. Keep the key format unambiguous so that two different input combinations cannot accidentally produce the same string.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsRank #4
- Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
- Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
- All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
- Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
- Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
Choosing an upstream or route
A map can derive a value consumed by proxying directives. For example, a header can select a logical backend class:
map $http_x_region $backend {
default app_default;
eu app_eu;
us app_us;
}
upstream app_default {
server 127.0.0.1:8000;
}
upstream app_eu {
server 127.0.0.1:8001;
}
upstream app_us {
server 127.0.0.1:8002;
}
server {
listen 80;
location / {
proxy_pass http://$backend;
}
}
When a variable is used in proxy_pass, confirm how your Nginx version resolves the resulting value and whether a resolver is required. Named upstream groups and DNS names do not follow identical resolution paths. If the input is client-controlled, map only to a finite set of known values; never let a request header become an arbitrary proxy destination.
For simpler routing, map to a URI, a feature flag or a header and keep the actual upstream choice in explicit location or proxy configuration. This makes the allowed destinations easier to audit.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Redirects, headers and access decisions
Build a redirect target
map $host $canonical_host {
default example.com;
www.example.com example.com;
example.com example.com;
}
server {
listen 80;
return 301 https://$canonical_host$request_uri;
}
Only map hosts that you intentionally serve. A broad default redirect can hide malformed or hostile host values; use a rejected default instead when unknown hosts must not be redirected.
Free tools Windows power users keep installed
One-click scans. No signup required.
Set a conditional response header
map $http_user_agent $legacy_client {
default 0;
~*MSIE 1;
}
server {
listen 80;
add_header X-Legacy-Client $legacy_client always;
}
The value can also feed a directive that accepts variables for cache behavior, logging or application metadata. Treat user-agent classification as advisory: it is easy for clients to forge.
Produce an access flag
map $http_x_internal_token $is_internal {
default 0;
trusted-token 1;
}
server {
listen 80;
location /admin/ {
if ($is_internal = 0) { return 403; }
proxy_pass http://admin_backend;
}
}
A map can supply the decision value, but authentication and authorization should not rely on a guessable header token. Prefer established identity controls, network restrictions and a secret-management design appropriate to the application.
Best Value
Keeping large maps maintainable
Move long lists into an included file while leaving the declaration and fallback visible:
map $http_x_tenant $backend_class {
include conf.d/tenant-map.conf;
default unknown;
}
The included file can contain ordinary map entries:
tenant-a standard;
tenant-b priority;
tenant-c isolated;
Multiple include directives are allowed. Keep generated data under version control, review changes as policy changes, and test for duplicate keys or unintended overlaps. A readable map should make the fallback, special cases and broad patterns obvious to the next operator.
Volatile maps and hash-table tuning
Map results are normally cacheable after evaluation for a request. The volatile; parameter marks the result variable as not cacheable; the reference documents this parameter as available since Nginx 1.11.7. Use it only when the source can change during the variable’s lifetime and repeated evaluation is intentional.
map $request_id $policy {
volatile;
default standard;
~^test- experimental;
}
For very large maps, map_hash_bucket_size and map_hash_max_size in the http context tune the hash tables. The documented default bucket size is 32, 64 or 128 depending on cache-line size; the documented maximum hash size is 2048. Increase these only after a configuration test identifies hash-sizing errors, and change one setting at a time.
Using map in the stream context
HTTP request maps and stream connection maps use the same general idea but different contexts. The stream module’s map belongs inside stream {} and derives values from connection-level variables.
stream {
map $remote_addr $limit {
default 10;
192.0.2.10 2;
}
limit_conn_zone $limit zone=per_class:10m;
}
Use the stream form for TCP or UDP connection policies, not for HTTP-only variables such as $uri or $http_host. The same precedence rules apply: exact entries, masks, regular expressions in written order and then default.
Map versus geo and numeric mapping
| Need | Prefer | Reason |
|---|---|---|
| String, hostname or regular-expression classification | map |
It derives a variable from text values and provides deterministic exact, mask, regex and default precedence. |
| IP-network or address-range classification | geo |
Address and network ranges are its intended input domain. |
| Numeric ranges | num_map where available |
Current Nginx documentation provides a separate module for numeric mapping. |
| Connection-level stream values | Stream map |
The declaration belongs in stream {} and can feed connection directives. |
Choosing the module that matches the input domain keeps the configuration understandable and avoids encoding numeric or network logic as fragile regular expressions.
Common failures and how to fix them
- “map directive is not allowed here.” Move the block into
http {}, or into a file included from that context. For connection mappings, usestream {}. - The result is empty. Add an explicit
default, then verify that the source variable contains the value you expect. An omitted default intentionally yields an empty string for unmatched input. - A wildcard unexpectedly wins. Check the exact-versus-mask precedence and whether the hostname pattern is enabled with
hostnames;. An exact key always takes priority over a mask. - The wrong regex matches. Regexes are evaluated in written order. Move the specific expression above the broad one, and choose
~or~*deliberately. - A capture has the wrong value. Positional captures share the request or connection capture set and can be overwritten. Use a named capture for values referenced later.
- A proxy target is rejected or resolved unexpectedly. A variable in
proxy_passchanges resolution behavior. Map only to approved destinations and check the resolver and upstream setup for your installed version. - A large map fails hash sizing. Keep the map valid first, then adjust
map_hash_bucket_sizeormap_hash_max_sizeinhttpand rerunnginx -t.
A practical design checklist
- Identify the input domain: text, hostname, IP network, number or stream connection value.
- Place the declaration in the correct context before writing consuming directives.
- Give the result variable a descriptive name that states what it represents.
- Write the safest fallback first in your design, then add exact exceptions.
- Use
hostnames;before hostname masks. - Keep regexes narrow and order them from most specific to most general.
- Prefer named captures when a regex value is needed later.
- Keep client-controlled inputs mapped to finite, reviewed outputs.
- Move large policy lists to included files and review them as configuration data.
- Run
nginx -t, reload only after a successful test, and exercise exact, wildcard, regex and fallback cases.
Key takeaways
Think of map as a lazy variable function: it reads one or more existing variables and returns a controlled value when another directive asks for it. Put HTTP declarations in http {}, define a deliberate default, enable hostnames; before hostname masks, and remember that exact keys outrank masks, masks outrank regexes, and regex order decides ties. Use stream maps for connection-level policy, keep large mappings in included files, and treat variable-driven proxy destinations as a security-sensitive design.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →




