$connection
The $connection variable returns the connection descriptor number for the current request in NGINX. — NGINX Core (HTTP)
Description
The $connection variable is a built-in variable in NGINX that gives you a unique connection identifier for each request processed by the server. It is particularly useful for debugging and logging, allowing administrators to track the connection details across multiple requests. The value is based on the socket descriptor and is an integer that varies with each instance of a connection. Every time a new request is handled, this variable is set to identify which connection is being used, hence it helps in identifying concurrent requests from the same client or differentiating between various users in a log file. During the request processing, when a client connects to the NGINX server, a connection object is created that holds various connection-related information such as the client's address, connection state, and more. The $connection variable directly correlates to this connection object. As each client may make multiple requests over a single connection, this variable is invaluable in contexts where connection-based logic is implemented, such as rate limiting, access control, and customized logging. Typical values of this variable are integer numbers specific to the system's current connections, and they can be linked to requests over HTTP/2 multiplexed streams as well, where the same connection can serve multiple requests simultaneously. Note that, since NGINX uses an asynchronous, event-driven model, the same $connection will be shared among requests until the connection is closed, at which point a new identifier will be assigned for new connections.
Config Example
server {
listen 80;
location / {
access_log /var/log/nginx/access.log;
log_format main '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$connection"';
}
}Subsystem
httpCacheable
YesContexts
http, server, location, ifUsing $connection in if statements can lead to unexpected behaviors, as the variable may not evaluate correctly in some contexts.
When using $connection for logging, ensure the accessed logs are appropriately formatted to handle multi-valued connections like HTTP/2.