Search code examples
phplaravelheroku

Failed to load CSS in HTTPS protocol


I created a blog using Laravel, and I am having a weird issue. I pushed my project to Heroku (nepshare.herokuapp.com). When I visit this URL my site loads but with no CSS and I refreshed every time to make it load but failed. Finally, I changed the https://nepshare.herokuapp.com URL to http://nepshare.herokuapp.com (changed from HTTPS to HTTP) then everything works just fine.css are only loaded in HTTP. How to render all CSS in HTTPS protocol? The following is my main layout code:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet" type="text/css">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>

@include('inc.navbar')
<div class="container">
    @include('inc.messages')
    @yield('content')
</div>

<script src="/vendor/unisharp/laravel-ckeditor/ckeditor.js"></script>
<script>
    CKEDITOR.replace('article-ckeditor');
</script>
</body>
</html>

Solution

  • In your .env file define new property,

    REDIRECT_HTTPS = true
    

    In your app/Providers/AppServiceProvider.php add this,

    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);
            }
        }
    }
    

    Now you can use,

    <script src="{{ asset('js/app.js') }}" defer></script>
    

    Or you can use secure_asset() helper function but secure_asset() method only use https: https://laravel.com/docs/5.1/helpers#method-secure-asset