nginx keep port number when 301 redirecting

喜夏-厌秋 提交于 2019-11-29 14:00:10

问题


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?


回答1:


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.




回答2:


For me, editing the following lines in proxy.conf to look like this, did the trick:

proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Host $http_host;


来源:https://stackoverflow.com/questions/43397365/nginx-keep-port-number-when-301-redirecting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!