The port_in_redirect parameter in NGINX

nginx port in redirect
06 February 2025

Introduction to the port_in_redirect parameter in NGINX


When working with the popular web server NGINX, it may happen that we encounter scenarios that require specific changes in URL handling. One of these important changes is managing redirects and formatting URLs using ports. Specifically, the port_in_redirect parameter in the ngx_http_core_module allows us to control how ports are displayed in redirects.


This parameter is set to on by default, meaning that NGINX will display the port in URLs that redirect back to users. This behavior can be altered and set to off; in this case, the port will not be shown in the URL. Alternatively, if the redirect is to an IP address or a domain name with a specific port, configuring this parameter can determine whether the port is included in the destination URL or not.


Assume that you have a website running on port 8080 on your server. If a user accesses the address http://example.com and you want this request to redirect them to http://example.com:8080, by using port_in_redirect, you can easily accomplish this. If you set this parameter to off, the use of port 8080 in redirects will not occur.


Utilizing this feature can be beneficial for users who do not want ports displayed in non-standard URLs, as it can enhance user experience and improve the aesthetics of URLs. Additionally, when specific SSL and HTTPS settings are present, managing ports can help reduce complexity.


Example of using port_in_redirect


server {
listen 80;
server_name example.com;

# Activating port_in_redirect
port_in_redirect on;

location / {
return 301 http://example.com:8080$request_uri;
}
}

Code Explanation


server {

Defines a new server block in NGINX.

listen 80;

Configures NGINX to listen on port 80.

server_name example.com;

Specifies the domain name that this server block is for.

port_in_redirect on;

Enables showing ports in redirects.

location / {

Defines a specific location (in this case, the root) for managing redirects.

return 301 http://example.com:8080$request_uri;

Creates a permanent redirect to a new URL that includes port 8080.

}

Ends the location block.

FAQ

?

Why should I use port_in_redirect?

?

Can I disable port_in_redirect?

?

How can I hide the port in redirects?

?

What is the difference between a permanent and temporary redirect?