0
0
Nginxdevops~30 mins

Map directive for variable mapping in Nginx - Mini Project: Build & Apply

Choose your learning style9 modes available
Map Directive for Variable Mapping in Nginx
📖 Scenario: You are configuring an Nginx web server to serve different content based on the client's IP address range. You want to use the map directive to create a variable that changes its value depending on the client's IP.
🎯 Goal: Build an Nginx configuration that uses the map directive to set a variable called $client_type to internal for IPs in the 192.168.1.0/24 range and external for all other IPs.
📋 What You'll Learn
Create a map block named client_type that maps $remote_addr to internal or external
Define the IP range 192.168.1.0/24 as internal
Set the default value to external
Use the $client_type variable inside the server block
Print the value of $client_type in the response header
💡 Why This Matters
🌍 Real World
In real web servers, the <code>map</code> directive helps customize responses based on client IPs, user agents, or other variables without changing the main server logic.
💼 Career
Knowing how to use <code>map</code> in Nginx is valuable for DevOps engineers and system administrators to implement flexible, efficient server configurations.
Progress0 / 4 steps
1
Create the basic Nginx server block
Write an Nginx configuration with a server block listening on port 8080 and a location / that returns a simple text response.
Nginx
Need a hint?

Start with a simple server block that listens on port 8080 and returns a text response.

2
Add a map directive to define $client_type
Add a map directive outside the server block that maps $remote_addr to internal for IP range 192.168.1.0/24 and sets the default to external. The variable name must be client_type.
Nginx
Need a hint?

The map directive must be placed outside the server block. Use the IP range 192.168.1.0/24 as the key and internal as the value.

3
Use the $client_type variable in the server block
Modify the location / block inside the server block to add a response header named X-Client-Type with the value of the $client_type variable.
Nginx
Need a hint?

Use the add_header directive inside the location / block to add the header.

4
Test the configuration output
Run the Nginx server with this configuration and simulate a request from IP 192.168.1.5. Print the response header X-Client-Type to confirm it shows internal.
Nginx
Need a hint?

Since this is a configuration file, simulate the output by printing the expected header line.