Can't redirect with status

好久不见. 提交于 2019-12-12 03:39:37

问题


Controller is called with

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

Inside it I tried:

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

or

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

but the response returned always has code 200. How to enforce 404 ?


回答1:


You cannot redirect with 404 status code. Only 3xx is valid for redirection. When browser receives a Location: header it makes a new request to the given url. This means you could however redirect to a route which 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);
});

Above code will redirect you to response with 404 status code.

$ 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!


来源:https://stackoverflow.com/questions/43006106/cant-redirect-with-status

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