Skip to main content

SOLVED: Force Assets to use HTTPS in Laravel

I have been doing some work with Laravel lately and needed to force a site to use https for everything. One of the first problems I encountered was figuring out how to force https in Laravel for linked stylesheets, javascript assets, etc…

I found a few different solutions, but none of them solved the issue. I was able to combine a couple of different approaches and found one that worked really well.

HTTPS in Laravel | Setup Asset and URL Helpers

Set an environment variable in your https environments
Since most people develop in a localhost/non https environment, I found that setting a boolean environment variable takes away the pain. I called mine REDIRECT_HTTPS. I set the value to true.

Update your app/Providers/AppServiceProvider.php file
As you will see below, I check the environment variable to enable the https settings. If set to true, the https prefix is added to your asset urls.


namespace App\Providers;

use Illuminate\Routing\UrlGenerator;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot(UrlGenerator $url)
    {
        if(env('REDIRECT_HTTPS')) {
            $url->formatScheme('https');
        }
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        if(env('REDIRECT_HTTPS')) {
            $this->app['request']->server->set('HTTPS', true);
        }
    }
}

Import your assets normally
After your have everything in place, you can just import your assets normally and they will load with https in https environments and http in non-https environments depending on your environment variable.


<!-- Stylesheet File Example -->
<link href="/%7B%7B%20asset('styles/main.css')%20%7D%7D" rel="stylesheet">

<!-- Script Import Example -->
<script src="/%7B%7B%20asset('scripts/app.js')%20%7D%7D"></script>

Learn Laravel

Before I started working on this project, my knowledge of the Laravel framework was very limited. I worked through a few examples, but was still left with a lot of questions about facades, helpers, the dependency injection mechanism, database migrations, security, etc…

When learning a new framework, my goto is normally Pluralsight. I will be writing a post with more training resources than the following, but wanted to recommend the following courses:

  1. Getting Started with Laravel (PHP Framework) – The Basics
  2. Getting Started with Laravel (PHP Framework) – Models and Data
  3. RESTful Web Services with PHP and Laravel

As always, please comment with questions, etc…

Comments

  1. Tzvetan

    Two years after, still the best solution I found

  2. Sata Lesmana

    thank for sharing, you are saved my life

Leave a Reply

Your email address will not be published. Required fields are marked *