$proxy_port

The $proxy_port variable returns the port number of the proxied server. — NGINX Core (HTTP)

$proxy_port NGINX Core (HTTP)

Description

The $proxy_port variable in NGINX is used to specify the port number of the proxied server that was specified in a proxy_pass directive. This variable is particularly useful when you need to log or conditionally handle requests based on the destination server's port. It is set whenever a request is proxied using the `proxy_pass` directive. If a hostname is given in `proxy_pass`, NGINX resolves this to an address and port, and the $proxy_port variable retrieves that port. Commonly, this port will be 80 for HTTP requests and 443 for HTTPS, but it can vary based on your upstream server's configuration. In scenarios where a request is not proxied, or if the port is not explicitly defined in the proxy_pass configuration, $proxy_port may return an empty string. It’s essential to ensure that your proxy_pass configuration correctly specifies a protocol and port to utilize this variable effectively. You can also combine it with other variables such as $proxy_host to create dynamic behaviors in your configurations.

Config Example

location /example {
    proxy_pass http://backend_server:8080;
    access_log /var/log/nginx/proxy_access.log "Proxy to port: $proxy_port";
}

Subsystem

http

Cacheable

No

Contexts

http, server, location, if

If no proxy is set or if the proxy_pass url doesn't specify a port, $proxy_port may return an empty value.

Remember to check conditional handling if you plan to use $proxy_port in if statements, as they can behave unexpectedly.