$remote_port

The $remote_port variable in NGINX contains the port number of the client making the request, used in access control and logging. — NGINX Core (HTTP)

$remote_port NGINX Core (HTTP)

Description

The $remote_port variable is a built-in NGINX variable that captures the TCP port number from which the client has established a connection to the server. It is primarily useful for logging and providing access control based on the source port of the requests. This variable is set as part of the request handling process, specifically when NGINX processes the incoming connection and initializes the request structure where various client-related details are stored. When a client connects to a server, the remote port is established by the operating system and made available to NGINX. In a typical scenario, this port number can range from 1024 to 65535, as ports in the range 1-1023 are reserved for well-known services. It can also vary frequently, as clients may connect from different applications or environments, leading to various port numbers being assigned. NGINX utilizes this variable in directives such as logging via the 'log_format' directive and in access control rules by allowing or denying requests based on source port ranges.

Config Example

server {
    listen 80;
    location / {
        access_log /var/log/nginx/access.log 'Client IP: $remote_addr, Port: $remote_port';
    }
}

Subsystem

http

Cacheable

Yes

Contexts

http, server, location, if

The value of $remote_port is not always predictable; it can vary between requests from the same client.

Using $remote_port in security rules should be done with caution; port spoofing can occur from client-side applications.

This variable is not available in all contexts; ensure you are using it in a correct context such as http, server, or location.