nginx keep port number when 301 redirecting

David Millar picture David Millar · Apr 13, 2017 · Viewed 13.7k times · Source

I'm trying to collapse a second brand of a web app into the first brand and use 301 redirects to redirect any lingering traffic. The server is running in a Vagrant box forwarding on port 8001. I would like to have:

Instead of https://local-dev-url:8001/foo/(anything) 301 to https://local-dev-url:8001/(anything)

Instead of https://local-dev-url:8001/adminfoo/(anything) 301 to https://local-dev-url:8001/admin/(anything).

Here's what I have:

    location ~ /foo/?(.*)$ {
        return 301 $1/;
    }

    location ~ /adminfoo/?(.*)$ {
        return 301 admin/$1/;
    }

    location / {
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Port 443;
        proxy_set_header Authorization $http_authorization;
        proxy_set_header X-Scheme $scheme;
        proxy_pass http://127.0.0.1:5000;
        proxy_redirect http:// $scheme://;
    }

    location /admin/ {
        alias /hostonly/path/to/admin/stuff/;
    }

However, instead of redirecting https://local-dev-url:8001/foo/ to https://local-dev-url:8001/ it is 301ing to https://local-dev-url// instead. (No port number, extra slash.) I've seen answers that hard-code the URL of the redirect, but since I work with a lot of other devs and we all have unique local dev URLs, the only consistent part is the :8001 port number.

Is there a way to configure the 301 to work as desired?

Answer

Richard Smith picture Richard Smith · Apr 13, 2017

If nginx is not listening on port 8001, it cannot know which port to use in the redirect. You will need to specify it explicitly:

location ~ /foo(.*)$ {
    return 301 $scheme://$http_host$1;
}
location ~ /adminfoo(.*)$ {
    return 301 $scheme://$http_host/admin$1;
}

The $http_host variable consists of the hostname and port from the original request. See this document for details.