I am trying to redirect old URLs with 301 response status. I am using Sim 4. I checked some previous topic, like: 214 but it’s not working for me.
My code:
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\App;
return function (App $app) {
$app->get('/', \App\Action\HomeAction::class)->setName('home');
// redirects
$app->get('/old-url', function (ServerRequestInterface $request, ResponseInterface $response) {
return $response->withRedirect('/new-url')->withStatus(301);
});
Of course, I get error because ResponseInterface doesn’t have withRedirect method.
When I check Response - Slim Framework there is usage of header Location which is I guess not my case, because I am not changing domain, just redirecting within the same domain.
How would you redirect in Slim 4 within the same domain from old URL to the new one?
Thank you.
To respect the basePath and output the URL for a given route you can use the RouteParser:
use Slim\Routing\RouteContext;
// Get RouteParser from request to generate the urls
$routeParser = RouteContext::fromRequest($request)->getRouteParser();
$location = $route->urlFor('home');
return $response
->withHeader('Location', $location)
->withStatus(301);
PS: For redirects you can also use the $app->redirect(...) helper method.