$server_port

The $server_port variable returns the port number on which the current request was received. — NGINX Core (HTTP)

$server_port NGINX Core (HTTP)

Description

The $server_port variable in NGINX is dynamically set during the processing of a request to represent the port on which the server is listening for incoming connections. It is particularly useful when configuring responses that may vary based on the port number, such as enabling specific response headers or applying firewall rules. The variable takes into consideration both the port specified in the configuration and the port used by the client to initiate the request, providing clarity in multiport setups. This variable is generally set when the server block is defined in the NGINX configuration file. For instance, if a server block is configured to listen on port 80, any requests arriving on that port will update the $server_port variable to 80. In contrast, if the server block listens on an alternate port such as 443 (commonly used for HTTPS), the variable will reflect that value. This makes $server_port essential in crafting configurations that rely on distinguishing between, for example, HTTP and HTTPS traffic, as well as when managing applications that can run on non-standard ports. Typical values of $server_port include 80 for HTTP, 443 for HTTPS, or any other user-defined port. The variable does not include the protocol (HTTP/HTTPS) but solely focuses on the port number itself, giving flexibility and specificity for a range of server configurations.

Config Example

server {
    listen 80;
    server_name example.com;

    location / {
        add_header X-Server-Port "$server_port";
    }
}

Subsystem

http

Cacheable

Yes

Contexts

http, server, location, if

Be mindful that the value of $server_port is determined at runtime, so it may differ from the configured listen port if a different port is used during a proxy or redirect operation.

If NGINX is behind a load balancer or proxy that alters the port, $server_port will reflect the port at which NGINX receives the request, not the external-facing port.