How to require a route to be https Slim3

So I want to force user authentication to use https. I found this but it so old I suspect its pre Slim3

Pre Slim I might have done something like this:

if( substr_compare($_SERVER['HTTP_HOST'], 'localhost', 0, 9) != 0 ) // don't force on dev machine { if($_SERVER["HTTPS"] != "on"){ header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]); exit(); } }

Anyone have any suggestions?


I would use some middleware for it.

Here is an example:

Thanks looks good as well as some of the other Middleware there. Can’t wait to dig in.


Hi, I’m a bit late… but it is a great question, this is what I did today (a middleware) , to solve the same problem for paths related to authentication. The rest of the app may be non secured.

<?php namespace DarthEv\Core\app\middleware; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ResponseInterface; ```php /** * This middleware forces declared paths * to be redirect with HTTPS * * @author marcelbonnet * */ final class RequireHttpsMiddleware { const SSL_REQUIRED_PATHS = [ 'login', 'logout', 'auth/notAuthenticated' ]; public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next){ if($request->getUri()->getScheme() !== 'https' && in_array($request->getUri()->getPath(), self::SSL_REQUIRED_PATHS ) ){ return $response ->withStatus(302) ->withHeader('Location' , 'https://' . $request->getUri()->getHost() . $request->getUri()->getBasePath() . '/' . $request->getUri()->getPath() ); } if($request->getUri()->getScheme() === 'https' && !in_array($request->getUri()->getPath(), self::SSL_REQUIRED_PATHS ) ){ return $response ->withStatus(302) ->withHeader('Location' , 'http://' . $request->getUri()->getHost() . $request->getUri()->getBasePath() . '/' . $request->getUri()->getPath() ); } return $next($request, $response); } } ```

We already use Apache rewrite rules in .htaccess, so is there a way to combine that to force https for whole site?
But in consideration of this advice