301重定向时nginx保留端口号 [英] nginx keep port number when 301 redirecting

查看:958
本文介绍了301重定向时nginx保留端口号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将网络应用程序的第二个品牌折叠为第一个品牌,并使用301重定向来重定向任何挥之不去的流量.服务器在端口8001上的Vagrant框转发中运行.我希望拥有:

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:

代替 https://local-dev-url:8001/foo /(任何内容) 301到 https://local- dev-url:8001/(任何内容)

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

代替 https://local-dev-url:8001/adminfoo /(任何内容) https://local-dev-url:8001/admin/(任何内容) .

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

这就是我所拥有的:

    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/;
    }

但是,而不是重定向 https://local-dev-url:8001/foo / https://local-dev-url:8001/ https://local-dev-url// . (没有端口号,额外的斜杠.)我已经看到了对重定向的URL进行硬编码的答案,但是由于我与许多其他开发人员一起工作,并且我们都有唯一的本地开发URL,因此唯一一致的部分是: 8001端口号.

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.

是否可以将301配置为按需工作?

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

推荐答案

如果nginx没有在端口8001上侦听,则它将不知道在重定向中使用哪个端口.您需要明确指定它:

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;
}

$http_host变量由原始请求中的主机名和端口组成.有关详细信息,请参见本文档.

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

这篇关于301重定向时nginx保留端口号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆