Prevent NGINX to remove the port

Gurkengewuerz picture Gurkengewuerz · Sep 15, 2016 · Viewed 7.3k times · Source

I want to keep the ServerName and Port dynamicly on my rewrite: Lets say the Firewall redirect port 8081 to 80. So, if i access the webserver for example with "192.168.1.123/frontend" or "my.domain.tld:8081/frontend" i should be redirect to "192.168.1.123/frontend/" or "my.domain.tld:8081/frontend/"

If i use the normal redirect rewrite ^(.*[^/])$ $1/ permanent; and i access with the port 8081 the port got removed. (I already tried port_in_redirect off;)

I use almost the default configuration:

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www/html;
        index index.php index.html index.htm index.nginx-debian.html;

        server_name _;
        rewrite ^(.*[^/])$ $1/ permanent;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

        location ~ \.php$ {
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                include fastcgi.conf;
        }
}

Thank you in anticipation!


SOLUTION: Thanks to the NGINX Mailing list! I fixed this problem with a rewrite rule:

if (-d $request_filename) {
    rewrite [^/]$ $scheme://$http_host$uri/ permanent;
}

Answer

Ghis picture Ghis · Aug 26, 2018

I finally found a solution to the problem you've well described. I made it work with URL rewriting, but it seemed a bit overkill.

So, for anyone having the same problem, it appears the cleanest solution would be to replace this :

proxy_set_header Host $host;

with this :

proxy_set_header Host $http_host;

With this setup, Nginx will keep the port in your redirections, no matter you firewall configuration.

Hope this helps. Cheers !