How to serve static content in Laravel 5 over https?

江枫思渺然 提交于 2019-12-14 02:56:29

问题


I've spent a ton of time trying to fix this but haven't had any luck so far. My app isn't loading css because of a mixed content error (The page at 'https://example.com/' was loaded over HTTPS, but requested an insecure stylesheet 'http://example.com/assets/css/magazine.min.css'. This request has been blocked; the content must be served over HTTPS). I know that I can load the assets by passing in true to the asset function but that would mean I would have to go to all the asset calls and change them. Is there a site wide setting I can configure so that it does https in production and http in local?

Thanks


回答1:


You can create something like ForceHttps middleware and than create condition for environment inside of it, like this:

public function handle($request, Closure $next)
{
    if (!\App::environment('local')) {
        \URL::forceSchema('https');
    }

    return $next($request);
}

Than add it to some route group or globally if you want.

NOTE: I would suggest to resolve this on your web server, not in Laravel




回答2:


Just use asset() helper to generate asset's URL. It will use the current protocol.

Do NOT force assets to be loaded by https, unless they are sensitive (which is almost never the case). That would be an overhead, because you usually care more of safe website content than safe assets. In other words, if you accept loading http website, you most likely accept http assets. Instead, consider using middleware to redirect http to https on each non-safe request.

This is the middleware I'm using myself:

public function handle($request, Closure $next)
{
    if (!$request->secure()) {
        return redirect()->secure($request->getRequestUri());
    }

    return $next($request);
}

If you wish to use it, please remember to fire it BEFORE attaching any cookies, that is before Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse middleware.




回答3:


I created app/Helpers/SiteHelpers.php containing a function that overrides the default asset() function.

<?php

/**
 * Overrides the default asset() method, which generates an asset path for the application.
 *
 * @param  string $path
 * @param  bool   $secure
 *
 * @return string
 */
function asset ($path, $secure = null) {
    if (Request::server('HTTP_X_FORWARDED_PROTO') == 'https' || Request::server('HTTPS') == 'on') {
        $secure = TRUE;
    }

    return app('url')->asset($path, $secure);
}

then added it on bootstrap/autoload.php above require __DIR__.'/../vendor/autoload.php'; so it would look like below:

require __DIR__.'/../app/Helpers/SiteHelpers.php';
require __DIR__.'/../vendor/autoload.php';

this is flexible depending on whether you are serving your static content on http or https



来源:https://stackoverflow.com/questions/37517892/how-to-serve-static-content-in-laravel-5-over-https

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!