问题
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