Enforce HTTPS scheme in Laravel 9

0
7525
Enforce HTTPS scheme in Laravel 9
Enforce HTTPS scheme in Laravel 9

Just another day for a Laravel 9 development tip. Today, I will show you how to enforce HTTPS scheme in Laravel 9 application such as assets, routes…

To enforce HTTPS scheme for a Laravel application, you can either:

  • Configure Web Server.
  • Configure Laravel App.

Let’s walk through both of them.

Configure Web Server

Depending on your server, Apache HTTP server or nginx, you will apply the appropriate config below for your Laravel application.

For Apache or .htaccess:

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

For nginx server:

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    return 301 https://example.com$request_uri;
}

Also, make sure to set the environment variable APP_URL in .env of your Laravel application to use HTTPS.

APP_URL=https://example.com

Restart web server and visit the site on browser to confirm if it works or not.

Configure Laravel App

To force HTTPS for all routes in Laravel application, we need to make some modification on app/Providers/AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    // ... other code

    public function boot()
    {
        $this->app['request']->server->set('HTTPS','on');
        URL::forceScheme('https');
    }
}

However, if you’re developing Laravel application locally, you might want to turn off HTTPS, which can be done via environment condition check.

public function boot()
{
    if ($this->app->environment('production')) {
        $this->app['request']->server->set('HTTPS','on');
        URL::forceSchema('https');
    }
}

This will only enforce HTTPS for production environment only.

Conclusion

Typically, it should work using either one of the methods. However, it is a good practice to apply both for server and Laravel application.

That’s how you enforce HTTPS scheme in Laravel 9 application.

Have fun!