I have a Slim 4 app and I'm trying to set up a middleware that redirects non https to https. So if I type
this_website.com
in the browser, this gets redirected automatically to https://this_website.com
I have an earlier website built with Slim 3 and I could use the following:
final class FullHttpsMiddleware {
public function __invoke($request, $handler) {
$response = $handler->handle($request);
if($request->getUri()->getScheme() !== 'https' ){
if($request->getUri()->getPath() != '/') {
$response = $response->withStatus(302)->withHeader('Location', 'https://' . $request->getUri()->getHost() . $request->getUri()->getBasePath() . '/' . $request->getUri()->getPath() );
} else {
$response = $response->withStatus(302)->withHeader('Location', 'https://' . $request->getUri()->getHost() . $request->getUri()->getBasePath() );
}
}
return $response;
}
}
The problem is that $request->getUri()->getBasePath()
doesn't exist in Slim 4. How can I change this code to work on Slim 4?
I wrote a blog post about this topic: Slim 4 - HTTPS Middleware
You could also use a .htaccess
file to redirect the http traffic to https.
If you have existing code in your .htaccess, add the following:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]