mladoux
11/23/2018 - 5:38 PM

Slim 3 Middleware - Force HTTPS

Slim 3 Middleware - Force HTTPS

// Enforce HTTPS
$app->add(function (Request $request,  Response $response, $next) {

  $cf = $this->get('settings');
  
  // Check if configuration wants us to enforce https, so we can turn it
  // on or off depending on whether the server supports https
  if (isset($cf['force_https']) && $cf['force_https'] === true) {
    if ($request->getUri()->getScheme() !== 'https') {
      // Redirect to HTTPS
      $uri = $request->getUri()->withScheme("https")->withPort(null);
      return $response->withRedirect( (string)$uri );
    }
  }
  return $next($request, $response);
});