HxHippy

Nginx Variables

Using built-in and custom variables in Nginx configuration.

Last updated: 2025-01-15

Common Built-in Variables

Request Variables

Variable Description
$request_uri Full original URI with arguments
$uri Current URI (can be modified)
$args Query string
$request_method GET, POST, etc.
$scheme http or https
$host Request host header
$server_name Name of server block

Client Variables

Variable Description
$remote_addr Client IP address
$remote_port Client port
$remote_user Auth basic username
$http_user_agent User-Agent header
$http_referer Referer header
$http_cookie Cookie header

Server Variables

Variable Description
$server_addr Server IP
$server_port Server port
$server_protocol HTTP/1.0, HTTP/1.1, HTTP/2
$nginx_version Nginx version
$document_root Root directive value

Using Variables

In Proxy Headers

location / {
    proxy_pass http://backend;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

In Logging

log_format custom '$remote_addr - [$time_local] '
                  '"$request" $status $body_bytes_sent '
                  'rt=$request_time';

access_log /var/log/nginx/access.log custom;

In Conditionals

# Check request method
if ($request_method = POST) {
    return 405;
}

# Check user agent
if ($http_user_agent ~* "bot") {
    return 403;
}

Map Directive

Create custom variables based on other variables:

# Set variable based on URI
map $uri $backend {
    default        http://app1;
    ~^/api/        http://app2;
    ~^/admin/      http://app3;
}

server {
    location / {
        proxy_pass $backend;
    }
}

Boolean Maps

# Check if mobile
map $http_user_agent $is_mobile {
    default 0;
    ~*mobile 1;
    ~*android 1;
    ~*iphone 1;
}

server {
    if ($is_mobile) {
        rewrite ^ /mobile$uri redirect;
    }
}

Set Directive

Define custom variables:

location / {
    set $proxy_host "backend.local";
    set $proxy_port "8080";

    proxy_pass http://$proxy_host:$proxy_port;
}

Geo Variables

Set variables based on client IP:

geo $allowed {
    default 0;
    192.168.1.0/24 1;
    10.0.0.0/8 1;
}

server {
    if ($allowed = 0) {
        return 403;
    }
}

Split Clients (A/B Testing)

split_clients "$remote_addr$request_uri" $variant {
    50% "A";
    50% "B";
}

server {
    location / {
        if ($variant = "A") {
            proxy_pass http://version_a;
        }
        if ($variant = "B") {
            proxy_pass http://version_b;
        }
    }
}
intermediate Core Concepts Updated 2025-01-15
  • nginx
  • variables
  • dynamic
  • request
  • headers