NGINX returns 一个 302 错误页面而不是进行 302 重定向

NGINX returns a 302 error page instead of make a 302 redirect

我的服务器块上有这个部分:

    location /mycoolurl {
             rewrite /mycoolurl(.*)  redirect;
    }

当有人在浏览器中尝试 http://coolserver/mycoolurl/ 它尝试重定向到:

http://coolserver/

此外,一切都像 http://coolserver/mycoolurl/foo/bar 重定向到:

http://coolserver/foo/bar

但是,如果我尝试访问 http://coolserver/mycoolurl 它显示了一个默认的 nginx 错误页面:

302 - Found

预期的行为是 302 重定向到 http://coolserver 而不是显示错误页面,因为这不是错误。

如何获得预期的行为?

当您尝试访问 /mycoolurl 时,您的正则表达式 (.*) 没有捕获任何内容。因此 Nginx returns "Location" header 中的空值连同 302 响应代码。大多数浏览器认为此组合不正确并显示错误。

为了防止这种情况,您需要修改您的重写规则,例如,这样:

location /mycoolurl {
    rewrite /mycoolurl/?(.*)$ / redirect;
}