Redirecting to HTTPS in Laravel 5

  • May 27, 2015

Welcome to the incredibly popular Easy Laravel 5 companion blog. To celebrate the new edition's release (updated for Laravel 5.5!) use the discount code easteregg to receive 20% off the book or book/video package! » Buy the book

These days it's pretty standard for a web application to include some level of user account integration. In order to protect the passage of account details such as the e-mail address and password, not to mention even more sensitive information such as credit card details, between the user's computer and the application server, you're going to want to encrypt the communications using SSL. Yet even after having successfully installed an SSL certificate it is likely still possible your users could navigate the web application using http:// rather than https://. Fortunately, you can easily configure a Laravel application to force all traffic through https://, and in this blog post I'll show you how.

There are actually a couple of different ways you can force SSL in conjunction with a Laravel application, however in my opinion the easiest approach involves updating the default .htaccess file included with every Laravel application. This .htaccess file is found in your project's .htaccess directory, and it looks like this:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews

    RewriteEngine On

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

The .htaccess file is responsible for ensuring two particularly important behaviors. First, it allows your Laravel application to use "pretty URLs" (/categories/12 as opposed to /categories.php?id=12) by enabling Apache's multi-view capability. Second, it routes all requests that are not for files (images, CSS, etc.) or directories through Laravel's front controller (index.php, which is also found in the public directory). Therefore prior to routing the request through the front controller you'll want to force SSL by adding the following lines:

# Force SSL
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Of course, if you're not using the Apache web server, then any changes you make to the .htaccess file is going to be irrelevant. In fact, even Laravel's own Homestead virtual machine uses Nginx rather than Apache. Fortunately, it's pretty easy to configure Nginx to force SSL, as demonstrated by this short configuration snippet:

server {
    listen       80;
    return       301$request_uri;

As mentioned, there are still other ways to configure Laravel applications to force SSL, including most notably custom middleware, however the method described above has been employed for years and is known to work flawlessly.