Unable to redirect with status

The controller is called using

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

Inside I tried:

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

or

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

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

0
source share
1 answer

You cannot redirect the status code 404. For redirection valid only 3xx. When the browser receives the header Location:, it makes a new request to the given URL. This means that you can redirect the route that 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);
});

The above code will redirect you to a response with a status code 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!
+1
source

Source: https://habr.com/ru/post/1675688/


All Articles