php 在 Laravel 中使用 https 加载 Blade 资源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34378122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:57:00  来源:igfitidea点击:

Load Blade assets with https in Laravel

phplaravelhttphttpslaravel-blade

提问by Artur Grigio

I am loading my css using this format: <link href="{{ asset('assets/mdi/css/materialdesignicons.min.css') }}" media="all" rel="stylesheet" type="text/css" />and it loads fine for all http requests

我正在使用这种格式加载我的 css: <link href="{{ asset('assets/mdi/css/materialdesignicons.min.css') }}" media="all" rel="stylesheet" type="text/css" />它可以为所有 http 请求加载

But when I load my login page with SSL (https), I get a ...page... was loaded over HTTPS, but requested an insecure stylesheet 'http...

但是当我使用 SSL (https) 加载我的登录页面时,我得到一个 ...page... was loaded over HTTPS, but requested an insecure stylesheet 'http...

Can someone please tell me how do I make blade load assets over https instead of http?

有人可以告诉我如何通过 https 而不是 http 使刀片加载资产吗?

Should I be trying to load the assets securely? Or is it not Blade's job?

我应该尝试安全地加载资产吗?或者这不是Blade的工作?

回答by Scofield

I had a problem with assetfunction when it's loaded resources through HTTP protocol when the website was using HTTPS, which is caused the "Mixed content" problem.

asset在网站使用HTTPS时通过HTTP协议加载资源时出现功能问题,这导致了“混合内容”问题。

To fix that you need to add \URL::forceScheme('https')into your AppServiceProviderfile.

要解决这个问题,您需要添加\URL::forceScheme('https')到您的AppServiceProvider文件中。

So mine looks like this (Laravel 5.4):

所以我的看起来像这样(Laravel 5.4):

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        if(config('app.env') === 'production') {
            \URL::forceScheme('https');
        }
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

This is helpful when you need https only on server (config('app.env') === 'production') and not locally, so don't need to force assetfunction to use https.

当您只需要在服务器 ( config('app.env') === 'production') 上而不是在本地asset使用 https时,这很有用,因此不需要强制函数使用 https。

回答by maiorano84

I believe secure_assetis what you're looking for.

我相信secure_asset是你正在寻找的。

<link href="{{ secure_asset('assets/mdi/css/materialdesignicons.min.css') }}" media="all" rel="stylesheet" type="text/css" />

5/15/2018 Edit:While my answer addresses the question directly, it's a bit dated given what Laravel can do nowadays; there may be cases where you want to force HTTPS on certain environments but not on others.

2018 年 5 月 15 日编辑:虽然我的回答直接解决了这个问题,但考虑到 Laravel 现在可以做的事情,它有点过时了;在某些情况下,您可能希望在某些环境中强制使用 HTTPS 而不是其他环境。

See Scofield's answer belowfor a more flexible solution to cover for these kinds of cases.

请参阅下面的 Scofield 的回答,以获取更灵活的解决方案来涵盖这些类型的情况。

回答by Abdul Rehman

I use @Scofield answer by use \URL::forceScheme('https');This solution also worked to show https for all routes but this not worked for me for $request->url() it show http instead of https

我使用@Scofield answer by use\URL::forceScheme('https');这个解决方案也可以显示所有路由的 https但这对我不起作用 $request->url() 它显示 http 而不是 https

so I used $this->app['request']->server->set('HTTPS', true);instead of \URL::forceScheme('https');

所以我用$this->app['request']->server->set('HTTPS', true);而不是\URL::forceScheme('https');

I'm using Laravel 5.4and update .env file and appserviceproviders

我正在使用 Laravel 5.4并更新.env 文件和 appserviceproviders

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
use Log;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     *
     */
    public function boot()
    {
        If (env('APP_ENV') !== 'local') {
            $this->app['request']->server->set('HTTPS', true);
        }

        Schema::defaultStringLength(191);
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

in my env file I've changed

在我的 env 文件中我已经改变了

APP_ENV=local to APP_ENV=development

APP_ENV=local for localhost APP_ENV=development/production for on working server

APP_ENV=local 用于本地主机 APP_ENV=development/production 用于工作服务器

after changing env run this artisan command

更改 env 后运行此工匠命令

php artisan config:clear

Hope It helps :-)

希望能帮助到你 :-)

回答by Ozan Kurt

An another approach would be to pass trueas the second parameter.

另一种方法是true作为第二个参数传递。

/**
 * Generate an asset path for the application.
 *
 * @param  string  $path
 * @param  bool    $secure
 * @return string
 */
function asset($path, $secure = null)
{
    return app('url')->asset($path, $secure);
}

As you see below secure_assetsimply calls assetwith the second parameter true.

正如您在下面看到的,secure_asset只需asset使用第二个参数调用即可true

/**
 * Generate an asset path for the application.
 *
 * @param  string  $path
 * @return string
 */
function secure_asset($path)
{
    return asset($path, true);
}

回答by Goran Siriev

The problem is cloudflare on my local machines is working fine but online server not solution is

问题是我本地机器上的 cloudflare 工作正常,但在线服务器不是解决方案

 public function boot()
    {

        if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&  $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
             \URL::forceScheme('https');
        }
    }

回答by Jan Richter

Figuring out if the current Requestis secure or not should not be your decision. Underlying Symfony\Component\HttpFoundation\Requesthas isSecuremethod that Laravel uses internally.

确定电流Request是否安全不应该是您的决定。底层Symfony\Component\HttpFoundation\RequestisSecureLaravel 内部使用的方法。

public function isSecure()
{
    if ($this->isFromTrustedProxy() && $proto = $this->getTrustedValues(self::HEADER_X_FORWARDED_PROTO)) {
        return \in_array(strtolower($proto[0]), array('https', 'on', 'ssl', '1'), true);
    }

    $https = $this->server->get('HTTPS');

    return !empty($https) && 'off' !== strtolower($https);
}

So if your server is not passing the HTTPSheader with On, it should be passing X-FORWARDED-PROTOand must be allowed by your TrustProxiesmiddleware.

因此,如果您的服务器未使用 传递HTTPS标头On,则它应该传递X-FORWARDED-PROTO并且必须由您的TrustProxies中间件允许。

If you are behind reverse-proxy you should find out your proxy pass IP - you can do this easily by getting the $_SERVER['REMOTE_ADDR']variable and setting the IP to your TrustProxiesmiddleware:

如果您使用反向代理,您应该找出您的代理传递 IP - 您可以通过获取$_SERVER['REMOTE_ADDR']变量并将 IP 设置为您的TrustProxies中间件来轻松完成此操作:

/**
 * The trusted proxies for this application.
 *
 * @var array
 */
protected $proxies = [
    '123.123.123.123',
];

Laravel (Symfony) will then automatically detect if the Requestis secure or not and choose the protocol accordingly.

Laravel (Symfony) 然后会自动检测它Request是否安全并相应地选择协议。

回答by Christiaan van Steenbergen

Here is my configuration to make HTTPS working with assets. To enable this in production add REDIRECT_HTTPS=true in the .env file.

这是我使 HTTPS 与资产一起工作的配置。要在生产中启用此功能,请在 .env 文件中添加 REDIRECT_HTTPS=true。

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        if(env('REDIRECT_HTTPS'))
        {
            \URL::forceScheme('https');
        }

        Schema::defaultStringLength(191);
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

回答by Rikj000

I ended up putting this in my blade file:

我最终把它放在我的刀片文件中:

@if(parse_url(url('/'), PHP_URL_SCHEME) == 'HTTPS')
    <link rel="stylesheet" href="{{ secure_asset('assets/css/slider.css') }}">
    <link rel="stylesheet" href="{{ secure_asset('assets/css/dropdown.css') }}">
@else
    <link rel="stylesheet" href="{{ asset('assets/css/slider.css') }}">
    <link rel="stylesheet" href="{{ asset('assets/css/dropdown.css') }}">
@endif

回答by Elias Mohammadi

While upgrading Laravel version from 5.4 to 5.5, I had the same issue.

在将 Laravel 版本从 5.4 升级到 5.5 时,我遇到了同样的问题。

Just add \URL::forceScheme('https');in app/Providers/AppServiceProvider.php. It worked.

只需添加\URL::forceScheme('https');app/Providers/AppServiceProvider.php。有效。

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     *
     */
    public function boot()
    {
        \URL::forceScheme('https');
    }
...