301重定向时,nginx保留端口号

Dav*_*lar 8 nginx http-status-code-301 vagrant server

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

而不是https:// local-dev-url:8001/foo /(任何) 301到https:// local-dev-url:8001 /(任何东西)

而不是https:// local-dev-url:8001/adminfoo /(任何) 301到https:// local-dev-url:8001/admin /(任何东西).

这就是我所拥有的:

    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/;
    }
Run Code Online (Sandbox Code Playgroud)

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

有没有办法配置301按需工作?

Ric*_*ith 20

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

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

$http_host变量由原始请求中的主机名和端口组成.请参阅此文档了解详细信息

  • 我在使用 `docker` 使用端口转发时遇到了这个问题。同样的概念在这里也适用。容器内的 nginx 正在侦听端口 80 并且转发了 docker 容器的端口,因此重定向时 nginx 将使用 80 。 (2认同)