Nginx-Style Header Variables

September 9, 2025 · View on GitHub

Easegress HTTPServer supports nginx-style variables in the setHeaders configuration, allowing you to dynamically populate HTTP headers with request information. This feature provides powerful capabilities for debugging, logging, routing decisions, and passing contextual information to backend services.

Overview

The nginx variable system in Easegress supports:

  • Request line variables (method, URI, query parameters)
  • Host and server variables
  • Client information (remote address, user agent)
  • Time and timestamp variables
  • Content and protocol information
  • HTTP header extraction
  • Query parameter extraction
  • Cookie value extraction
  • Default value support with ${variable:default} syntax
  • String interpolation for building complex values

Easegress adopts nginx variables as much as possible for compatibility. For a complete reference of nginx variables, see the official nginx variable index.

Variable Syntax

Easegress supports two nginx-compatible variable syntaxes:

# Simple variable reference
X-Method: "$request_method"

# Variable with default value
X-Version: "${arg_version:v1.0}"

# String interpolation
X-Backend-URL: "${scheme}://${host}-backend${uri}"

Complete Example

See the complete example configuration at: example/config/test-nginx-header-vars.yaml

This example demonstrates all available variable types and usage patterns.

Variable Categories

1. Request Line Variables

Extract information from the HTTP request line:

VariableDescriptionExample Value
$request_methodHTTP methodGET, POST, PUT
$request_uriFull request URI with query string/api/users?page=1
$uriPath portion of URI (without query)/api/users
$schemeProtocol schemehttp, https
$query_stringQuery string portionpage=1&limit=10
$argsAlias for $query_stringpage=1&limit=10
$requestFull request lineGET /api/users HTTP/1.1

2. Host and Server Variables

Information about the server and request host:

VariableDescriptionExample Value
$hostHost from request (without port)api.example.com
$hostnameAlias for $hostapi.example.com
$http_hostHost header value (with port)api.example.com:8080
$server_nameServer nameapi.example.com
$server_protocolHTTP protocol versionHTTP/1.1, HTTP/2.0

3. Client Information Variables

Information about the client making the request:

VariableDescriptionExample Value
$remote_addrClient IP address192.168.1.100
$remote_userAuthenticated usernamejohn_doe
$proxy_add_x_forwarded_forX-Forwarded-For with client IP10.0.0.1, 192.168.1.100

4. Time and Timestamp Variables

Current time in various formats:

VariableDescriptionExample Value
$time_iso8601ISO 8601 timestamp2025-09-05T10:30:45+08:00
$time_localLocal time format05/Sep/2025:10:30:45 +0800
$msecTimestamp in milliseconds1725508245123
$request_timeRequest processing time0.045

5. Content and Protocol Variables

Information about request content:

VariableDescriptionExample Value
$content_typeContent-Type headerapplication/json
$content_lengthContent-Length header1024
$request_lengthTotal request size1024

6. HTTP Header Variables

Extract any HTTP header using the $http_ prefix:

Variable PatternDescriptionExample
$http_user_agentUser-Agent headerMozilla/5.0 (...)
$http_acceptAccept headerapplication/json
$http_x_forwarded_forX-Forwarded-For header10.0.0.1
$http_authorizationAuthorization headerBearer token123
$http_*Any header (replace * with header name)Various

Note: Header names are converted using these rules:

  • Convert to lowercase
  • Replace hyphens with underscores
  • Add http_ prefix

Examples:

  • Content-Type$http_content_type
  • X-API-Key$http_x_api_key
  • User-Agent$http_user_agent

7. Query Parameter Variables

Extract query parameters using the $arg_ prefix:

Variable PatternDescriptionExample
$arg_pageExtract page parameter1
$arg_limitExtract limit parameter50
$arg_api_keyExtract api_key parameterabc123
$arg_*Any query parameterVarious

Example URL: https://api.example.com/users?page=2&limit=50&api_key=abc123

Extract cookie values using the $cookie_ prefix:

Variable PatternDescriptionExample
$cookie_session_idExtract session_id cookiesess_abc123
$cookie_user_prefExtract user_pref cookiedark_mode
$cookie_*Any cookie valueVarious

9. Path Parameter Variables

Extract path parameters from route patterns (when using parameterized routes):

VariableDescriptionExample
$idPath parameter id123
$namePath parameter namejohn
Custom namesBased on route definitionVarious

Default Values

Use the ${variable:default} syntax to provide fallback values:

setHeaders:
  X-Version: "${arg_version:v1.0}"          # Default to "v1.0" if no version param
  X-User: "${remote_user:anonymous}"        # Default to "anonymous" if not authenticated
  X-Content-Type: "${content_type:none}"    # Default to "none" if no content type

Complex String Building

Combine multiple variables to build complex header values:

setHeaders:
  # Build backend URL
  X-Backend-URL: "${scheme}://${host}-backend${uri}"

  # Client information summary
  X-Client-Info: "IP: ${remote_addr}, Agent: ${http_user_agent:unknown}"

  # Request summary
  X-Request-Summary: "Method=${request_method}, Host=${host}, Path=${uri}, Client=${remote_addr}"

  # Proxy chain information
  X-Proxy-Chain: "Forwarded: ${proxy_add_x_forwarded_for}"

  # Processing information
  X-Processing-Time: "Started at ${time_iso8601} using ${server_protocol}"

Usage Examples

Basic Request Information

kind: HTTPServer
name: basic-vars-demo
port: 10080
rules:
  - paths:
    - pathPrefix: /
      backend: my-backend
      setHeaders:
        X-Method: "$request_method"
        X-Path: "$uri"
        X-Client-IP: "$remote_addr"
        X-Timestamp: "$time_iso8601"

API Gateway Headers

setHeaders:
  # API versioning
  X-API-Version: "${arg_version:v1}"
  X-API-Key: "${http_x_api_key:none}"

  # Request tracking
  X-Request-ID: "${http_x_request_id:auto-generated}"
  X-Trace-ID: "${http_x_trace_id:${time_msec}}"

  # Client information
  X-Client-IP: "$remote_addr"
  X-User-Agent: "$http_user_agent"
  X-Forwarded-For: "$proxy_add_x_forwarded_for"

Debugging Headers

setHeaders:
  # Full request debugging
  Debug-Method: "$request_method"
  Debug-URI: "$request_uri"
  Debug-Query: "$query_string"
  Debug-Host: "$http_host"
  Debug-Content-Type: "${content_type:none}"
  Debug-Content-Length: "${content_length:0}"
  Debug-User-Agent: "$http_user_agent"
  Debug-Request-Time: "$request_time"

Load Balancer Headers

setHeaders:
  # Upstream information
  X-Upstream-Server: "${scheme}://${host}"
  X-Original-Host: "$http_host"
  X-Original-URI: "$request_uri"

  # Load balancing info
  X-LB-Method: "roundrobin"
  X-LB-Timestamp: "$time_iso8601"
  X-Client-Real-IP: "$remote_addr"

Testing Variables

To test your nginx variables configuration:

  1. Apply the configuration:

    egctl create -f example/config/test-nginx-header-vars.yaml
    
  2. Send test requests:

    # Basic request
    curl -H "User-Agent: MyApp/1.0" \
         -H "X-API-Key: test123" \
         "http://localhost:10080/api/users?page=1&debug=true"
    
    # Request with cookies
    curl -H "Cookie: session_id=sess_abc123; user_pref=dark_mode" \
         "http://localhost:10080/profile"
    
    # POST request with content
    curl -X POST \
         -H "Content-Type: application/json" \
         -d '{"name":"test"}' \
         "http://localhost:10080/api/create"
    
  3. Check backend logs to see the populated header values.

Best Practices

1. Use Default Values

Always provide sensible defaults for variables that might not be present:

X-Version: "${arg_version:v1.0}"       # Good
X-Version: "$arg_version"              # Bad - might be empty

2. Sanitize Sensitive Information

Be careful with variables that might contain sensitive data:

# Good - mask sensitive tokens
X-Auth-Present: "${http_authorization:false}"

# Bad - might expose sensitive data
X-Auth-Token: "$http_authorization"

3. Use Descriptive Header Names

Choose clear, descriptive header names:

X-Client-IP: "$remote_addr"            # Good
X-IP: "$remote_addr"                   # Less clear

Organize headers logically:

setHeaders:
  # Client information
  X-Client-IP: "$remote_addr"
  X-Client-Agent: "$http_user_agent"

  # Request information
  X-Request-Method: "$request_method"
  X-Request-Path: "$uri"

  # Timing information
  X-Request-Time: "$time_iso8601"

Common Use Cases

1. Microservices Communication

Pass request context to downstream services:

setHeaders:
  X-Original-Method: "$request_method"
  X-Original-URI: "$request_uri"
  X-Client-IP: "$remote_addr"
  X-Request-ID: "${http_x_request_id:${msec}}"

2. Security Headers

Add security and tracking information:

setHeaders:
  X-Forwarded-Proto: "$scheme"
  X-Real-IP: "$remote_addr"
  X-Forwarded-For: "$proxy_add_x_forwarded_for"
  X-Request-Start: "$msec"

3. API Gateway

Standardize API request information:

setHeaders:
  X-API-Gateway: "easegress"
  X-API-Version: "${arg_version:v1}"
  X-Client-ID: "${http_x_client_id:anonymous}"
  X-Rate-Limit-Key: "${remote_addr}-${http_x_api_key:none}"

4. Debugging and Monitoring

Add comprehensive debugging information:

setHeaders:
  X-Debug-Method: "$request_method"
  X-Debug-Path: "$uri"
  X-Debug-Query: "$query_string"
  X-Debug-Client: "$remote_addr"
  X-Debug-Timestamp: "$time_iso8601"
  X-Debug-Protocol: "$server_protocol"

See Also