Port is lost when running Mautic behind proxy

Your software
My Mautic version is: 3.1.0
My PHP version is: 7.3.22

Your problem
I have problems with getting weird results when Mautic is behind Nginx proxy. I have Mautic running on Docker with on Nginx, container port 5000 is mapped to port 8100(localhost) and I want to proxy it to port 8877(also localhost for tests). The problem is that for some reason Mautic does redirect from localhost:8877 to localhost/s/login instead of localhost:8877/s/login, dropping the port completely and ending with connection refused. Requests to port 8100 work, to 8877 not at all.
I also have a problem when using Nginx TLS proxy, Mautic redirects from http://address:5000 to https://address/, dropping port and also changing from http to https for some reason, unfortunately I am not able to get configuration of TLS proxy but I guess the problem is similar.

Here is nginx.conf of Mautic Nginx

worker_processes  5;
worker_rlimit_nofile 8192;

error_log  /dev/stderr;

pid /tmp/nginx.pid;

events {
  worker_connections  4096;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    client_body_buffer_size 1024M;
    client_max_body_size 1024M;

server {
    listen         5000;
    server_name    example.com www.example.com;
    root           /var/www/html;
    index          index.php;
    error_page 404 /index.php;
    proxy_set_header Host $http_host;

  location / {
           try_files $uri /index.php$is_args$args;
  }

  location ~* \.php$ {
    fastcgi_pass  127.0.0.1:9000;

    include         fastcgi_params;
    fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
    fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
  }
}


}

Here is my Nginx proxy config:

worker_processes  5;
worker_rlimit_nofile 8192;

events {
  worker_connections  4096;
}

http {
server {
        listen 8877;

        location / {
                proxy_pass http://localhost:8100;

                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header Host $host;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "Upgrade";
       }
}
}

These errors are showing in the log:
I can see that Mautic receives correctly the request but it does 302 redirect(port dropping) or 301 redirect(both port dropping and https redirect).

Steps I have tried to fix the problem:
I tried various Mautic Nginx configs shared by other people, none of them works correctly.

EDIT:
It seems that the problem may be because of bad “Location” headers that store absolute paths with full URLs instead of relative paths, is there a way to fix it?

This is more a Ngnix issue than a Mautic issue. You should post this on Ngnix forums and see if you get help there.