无法重定向状态

Can't redirect with status

控制器被调用

$this->get( '/read/{slug}', \Rib\Src\Apps\Blog\BlogControllers\IndexController::class . ':index' );

我在里面试过:

return $response->withStatus( 404 )->withRedirect( '/message' );

return $response->withRedirect( '/message', 404 );

但返回的响应总是有代码 200。 如何执行 404?

您不能使用 404 状态代码进行重定向。只有 3xx 对重定向有效。当浏览器收到 Location: header 时,它会向给定的 url 发出新请求。这意味着您可以重定向到 returns 404.

的路线
$app->get("/test", function ($request, $response, $arguments) {
    return $response->withRedirect("/message");
});

$app->get("/message", function ($request, $response, $arguments) {
    return $response->write("Oh noes!")->withStatus(404);
});

以上代码会将您重定向到带有 404 状态代码的响应。

$ curl --include --location http://0.0.0.0:8080/test

HTTP/1.1 302 Found
Host: 0.0.0.0:8080
Date: Sun, 26 Mar 2017 04:53:05 +0000
Connection: close
X-Powered-By: PHP/7.1.2
Content-Type: text/html; charset=UTF-8
Location: /message

HTTP/1.1 404 Not Found
Host: 0.0.0.0:8080
Date: Sun, 26 Mar 2017 04:53:05 +0000
Connection: close
X-Powered-By: PHP/7.1.2
Content-Type: text/html; charset=UTF-8

Oh noes!