port_in_redirect

The `port_in_redirect` directive controls whether the port number of the request is included in redirects generated by NGINX.

Syntaxport_in_redirect on | off;
Defaultoff
Contexthttp, server, location
Argumentsflag

Description

The port_in_redirect directive is utilized to determine how NGINX handles the port number in redirection responses generated by the server. By setting this directive to on, NGINX includes the port number in the Location header of any redirect responses it generates if the server is listening on a non-standard port. This is particularly useful for accurately guiding clients to the correct host and port in cases where the web server is not operating on the default HTTP (80) or HTTPS (443) ports. Conversely, when set to off, the port number is omitted from the redirect URL, which means that clients may default to the standard ports when following the redirect.

In practical terms, this directive can be critical for ensuring that clients receive proper redirection when accessing services that are configured to use non-default ports, as failing to include the port could lead to confusion or failed requests. It is applicable in http, server, and location contexts, allowing for flexibility based on specific server or path requirements. Adjusting the port_in_redirect setting helps to resolve ambiguities that may arise due to complex server setups with multiple services running on different ports.

Config Example

server {
    listen 8080;
    port_in_redirect on;
    location / {
        return 301 http://example.com;
    }
}

Using this directive without understanding the implications of omitting the port can lead to unexpected behavior for clients following redirects.

If your server is running on default ports, setting this directive to on could expose the port unnecessarily in responses.

Be cautious when mixed with HTTPS configurations and non-standard ports.

← Back to all directives