Search code examples
httpsslimmiddleware

https not working with Slim


I have recently setup my EC2 LAMP server with SSL which works fine with Slim. I can securely log in to phpMyAdmin and see my data just fine too. However I get 504 gateway time out error on my routes that connect to mysql. My routes work fine when the same index.php file is on my local XAMPP server (which is not SSL enabled). So it appears to me that the https protocol is not yet working on LAMP server. Looking around I have seen things about modifying my .htaccess file to rewrite for https:

RewriteEngine on
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]`

but this has not made any difference and I have no idea why. Middleware has also come up too, to redirect http to https and this seems like a good option, but I have no idea where to begin with it.


Solution

  • I would simplify the .htaccess file a little bit and move the SSL check and redirect to a middleware.

    Content of .htaccess

    # Redirect to front controller
    RewriteEngine On
    # RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [QSA,L]
    

    Middleware

    // Redirect HTTP traffic to HTTPS
    $app->add(function (Request $request, Response $response, $next) {
        $uri = $request->getUri();
        if($uri->getScheme() !== 'https') {
            // Map http to https
            $httpsUrl = $uri->withScheme('https')->withPort(443)->__toString();
    
            // Redirect to HTTPS Url
            return $response->withRedirect($httpsUrl);
        }
    
        return $next($request, $response);
    });