Using Nginx Variables
1. Understanding Built-in Variables
| Variable | Description | Example Value |
|---|---|---|
| args | Query string parameters | name=John&age=30 |
| uri | Current URI being processed | /index.html |
| request_method | HTTP method used for the request | GET |
| http_host | Host header from the client request | example.com |
| http_user_agent | User agent string from the client | Mozilla/5.0... |
| remote_addr | IP address of the client | 192.168.1.100 |
| server_addr | IP address of the server | 10.0.0.5 |
| server_port | Port on which the server is listening | 80 |
| request_time | Time taken to process the request | 0.045 |
| status | HTTP status code of the response | 200 |
Example: Using Variables in Location Blocks
location /api/ {
proxy_pass http://backend/$uri;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
Note: Built-in variables are read-only and can be used in configurations but not modified.
2. Using Request Variables
| Variable | Description | Example Value |
|---|---|---|
| args | Query string parameters | name=John&age=30 |
| query_string | Same as args |
name=John&age=30 |
| uri | Current URI being processed | /index.html |
| request_uri | Original request URI including query string | /index.html?name=John&age=30 |
| request_method | HTTP method used in the request | GET |
| http_user_agent | User agent string from the client | Mozilla/5.0 (Windows NT 10.0; Win64; x64) |
| http_referer | Referer header from the client | https://example.com/page |
| remote_addr | IP address of the client | 192.168.1.100 |
| remote_port | Port number of the client | 54321 |
| server_addr | Server's IP address | 10.0.0.1 |
| server_port | Server's port number | 80 |
| scheme | Protocol used (http or https) | https |
| host | Host header from the request | example.com |
| server_name | Name of the server block matched | example.com |
| request_time | Time taken to process the request in seconds | 0.056 |
| upstream_response_time | Time taken to get response from upstream server | 0.045 |
| status | Response status code | 200 |
Example: Using Variables in Location Block
location /api {
proxy_pass http://backend;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
}
Example: Logging Request Variables
log_format custom '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"';
Note: Variables can be used in configuration directives to dynamically set values based on request context.
3. Using Client Variables
| Variable | Description | Example Value |
|---|---|---|
| remote_addr | Client's IP address | 192.168.1.100 |
| remote_port | Client's port number | 54321 |
| http_user_agent | User agent string from the client | Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 |
| http_referer | Referer URL sent by the client | https://example.com/page |
| http_host | Host header sent by the client | www.example.com |
| http_cookie | Cookie data sent by the client | sessionid=abc123; user=john |
Example: Logging Client IP Address
access_log /var/log/nginx/access.log main;
log_format main '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"';
Note: The
http_user_agent variable can be used to detect and block known bots or crawlers.
4. Using Server Variables
| Variable | Description | Example Value |
|---|---|---|
| server_name | Name of the server block that handled the request | example.com |
| server_port | Port on which the server is listening | 80 |
| server_addr | IP address of the server socket | 192.168.1.100 |
| server_protocol | Protocol used (e.g., HTTP/1.1) | HTTP/1.1 |
Example: Logging Server Name
access_log /var/log/nginx/access.log combined;
error_log /var/log/nginx/error.log;
location / {
proxy_pass http://backend;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Server-Name $server_name;
}
Note: Server variables can be used in configuration directives like
proxy_set_header, return, and rewrite.
5. Using Upstream Variables
| Variable | Description | Example Value |
|---|---|---|
| upstream_addr | Address of the upstream server | 192.168.1.10:8080 |
| upstream_status | Status code returned by the upstream server | 200 |
| upstream_response_time | Time taken to get a response from the upstream server | 0.045 |
| upstream_connect_time | Time taken to connect to the upstream server | 0.012 |
Example: Logging Upstream Variables
log_format upstream '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$upstream_addr" "$upstream_status" $upstream_response_time';
access_log /var/log/nginx/access.log upstream;
Note: These variables are only available in the context of an
upstream block or when proxying requests to upstream servers.
6. Using SSL Variables
| Variable | Description | Example Value |
|---|---|---|
| ssl_protocol | SSL/TLS protocol version used by the client | TLSv1.2 |
| ssl_cipher | SSL cipher suite used by the client | ECDHE-RSA-AES256-GCM-SHA384 |
| ssl_ciphersuites | Supported TLS 1.3 ciphersuites (if applicable) | TLS_AES_256_GCM_SHA384 |
| ssl_session_reused | Indicates if the SSL session was reused | yes |
| ssl_client_cert | Client certificate in PEM format (if available) | |
| ssl_client_verify | Result of client certificate verification | SUCCESS |
| ssl_client_s_dn | Subject distinguished name of the client certificate | /CN=example.com/O=Example Inc./ST=CA/C=US |
| ssl_client_i_dn | Issuer distinguished name of the client certificate | /CN=CA.example.com/O=Example CA/ST=CA/C=US |
| ssl_client_serial | Serial number of the client certificate | 1234567890ABCDEF |
| ssl_client_not_before | Start date of the client certificate validity | Jun 15 09:00:00 2024 GMT |
| ssl_client_not_after | End date of the client certificate validity | Jun 15 09:00:00 2025 GMT |
Example: Logging SSL Variables
error_log /var/log/nginx/error.log debug;
log_format ssl_log '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'ssl_protocol=$ssl_protocol ssl_cipher=$ssl_cipher';
access_log /var/log/nginx/access.log ssl_log;
Example: Redirecting Based on SSL Protocol
server {
listen 443 ssl;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
if ($ssl_protocol = "SSLv2") {
return 403;
}
location / {
proxy_pass https://backend;
}
}
Note: The
ssl_client_cert variable is only available when client certificate authentication is enabled.
Warning: Ensure that sensitive SSL variables like
ssl_client_cert are not logged in plain text without proper encryption or access controls.
7. Using Time Variables
| Variable | Description | Example Value |
|---|---|---|
| $time_iso8601 | Current time in ISO 8601 format (e.g., 2025-04-05T14:30:00+00:00) | 2025-04-05T14:30:00+00:00 |
| $time_local | Current time in local format (e.g., 05/Apr/2025:14:30:00 +0000) | 05/Apr/2025:14:30:00 +0000 |
| $time_gmt | Current time in GMT format (e.g., 05/Apr/2025:14:30:00 +0000) | 05/Apr/2025:14:30:00 +0000 |
Example: Logging with Time Variables
access_log /var/log/nginx/access.log "$remote_addr - $remote_user [$time_local] "
"$request" $status $body_bytes_sent "$http_referer" "$http_user_agent";
8. Creating Custom Variables
Custom variables in Nginx are created using the set directive. These variables can be used throughout the configuration to store and reuse values.
| Directive | Syntax | Description |
|---|---|---|
| set | set $variable_name value; |
Creates a new variable with the specified value |
Example: Setting a Custom Variable
location / {
set $greeting "Hello, World!";
return 200 $greeting;
}
Example: Using Variables in Headers
location / {
set $user_agent $http_user_agent;
add_header X-User-Agent $user_agent;
}
Note: Custom variables are created at the beginning of a request and can be used in any context within that request scope.
9. Using Map Directive
| Directive | Description | Example |
|---|---|---|
| map | Defines a mapping from one string to another, typically used for variable assignments based on input values. | |
Example: Basic Map Usage
map $http_user_agent $mobile {
default 0;
~"Mobile" 1;
}
server {
listen 80;
location / {
if ($mobile = 1) {
return 301 /mobile/;
}
}
}
Note: The
map directive is processed during Nginx startup and can be used to define variables that are evaluated at request time.
Map Directive Summary
- map creates a variable based on a mapping from an input string to a value.
- Supports regex matching with
~and case-insensitive matching with~*. - Can be used to set variables for conditional logic or URL rewriting.
10. Using Geo Directive
| Directive | Description | Example |
|---|---|---|
| geo | Defines a variable based on the client's IP address using a database or custom mapping. | |
| geoip_country | Maps IP address to country code using the GeoIP database. | |
| geoip_city | Maps IP address to city name using the GeoIP database. | |
Example: Using geo with country code
geo $country {
default "unknown";
127.0.0.1 "localhost";
192.168.0.0/16 "internal";
}
map $country $allowed {
"localhost" 1;
"internal" 1;
default 0;
}
location / {
if ($allowed = 0) {
return 403;
}
}
Note: The
geo directive is part of the ngx_http_geo_module. Ensure the GeoIP database is installed and configured for accurate IP lookups.
11. Understanding Variable Evaluation
| Variable | Evaluation Context | Description |
|---|---|---|
| uri | Request | Current URI being processed |
| request_method | Request | HTTP method used (GET, POST, etc.) |
| http_host | Request | Host header from the client request |
| args | Request | Query string parameters |
| server_addr | Connection | IP address of the server socket |
| remote_addr | Connection | IP address of the client making the request |
Note: Variables in Nginx are evaluated at different stages of the request processing. Some variables like
uri and args are evaluated on each request, while others like server_addr remain constant for the duration of a connection.
12. Using Regex Captures in Variables
| Variable | Description | Example |
|---|---|---|
| $1, $2, ..., $9 | Backreferences to captured groups in regex patterns | if ($uri ~* ^/user/([^/]+)/profile$) { return 301 /user/$1; } |
| $args | Query string parameters | rewrite ^/search/(.*)$ /search?$args&query=$1 last; |
Example: Capturing and Using URI Components
location ~ ^/api/v([0-9]+)/(user|admin)/(.+)$ {
set $version $1;
set $type $2;
set $path $3;
proxy_pass http://backend-$type-$version/$path;
}
Note: The variables
$1 through $9 are only available in the context of regex captures within if, rewrite, and similar directives.
Warning: These backreferences are not available in all contexts. They work in
rewrite and if blocks but not in regular variable assignments.