是否可以在 Laravel asset() 函数中添加 cdn.mydomain.com/assets ?

Is it possible to add cdn.mydomain.com/assets in Laravel asset() function?

我希望将我网站的资产加载为 cdn.mydomain.com/asset_path 而不是 mydomain.com/asset 路径。

不使用任何云 CDN。

总之我想要这个<img src="{{asset('/js/app.js')}}" > =<img src="mydomain.com/js/app.js" >

成为这种形式

<img src="{{asset('/js/app.js')}}" > =<img src="cdn.mydomain.com/js/app.js" >

请也看看这个包,它的作用相同,但 laravel 8 不支持 https://github.com/damianromanowski/simplecdn

如有任何帮助,我们将不胜感激。 提前致谢

注:我用的是Laravel 8

您可以通过在 .env 文件中设置 ASSET_URL 变量来配置资产 URL 主机。如果您将资产托管在 Amazon S3 或其他 CDN 等外部服务上,这会很有用:

// ASSET_URL=http://cdn.mydomain.com

$url = asset('js/app.js'); // http://cdn.mydomain.com/js/app.js

https://laravel.com/docs/8.x/helpers#method-asset

我自己通过添加中间件和更改发送到浏览器的响应来解决。

灵感来自上述包。

<?PHP

  namespace App\Http\Middleware;

  use Closure;
  use Illuminate\Http\Request;

 class CdnMiddleware
 {
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle(Request $request, Closure $next)
{
    $response = $next($request);
    $output = $response->getOriginalContent();
    $rules = array(

        array(
            // 'url'        => array('http://images.example.com/', 'http://images2.example.com/'),
            // 'remove' => 'assets/images/',
            'pattern'   => 'png|tif|tiff|gif|jpeg|jpg|jif|jfif|jp2|jpx|j2k|j2c|ico',
            'enabled'   => true
        ),
        
        array(
            'pattern'   => 'css',
            'enabled'   => true
        ),
        
        array(
            'pattern'   => 'js',
            'enabled'   => true
        ),
        
        array(
            'pattern'   => 'asf|avi|flv|m1v|m2v|m4v|mkv|mpeg|mpg|mpe|ogg|rm|wmv|mp4|webm',
            'enabled'   => true
        )
        
        );
        $url =  array(

            'http://cdn.my-domain.com/'
    
        );
    if (is_string($output) || method_exists($output, '__toString')) {
        $urls = preg_match_all("#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|[^[:punct:]\s]|/)#", $output, $matches);

        foreach ($matches[0] as $uri)
            foreach ($rules as $group)
                if (@$group['enabled'] && preg_match('/\.(' . @$group['pattern'] . ')(?:[\?\#].*)?$/i', $uri, $matchess))
                {
                    $config_url = $url;

                    $config_remove = '';
                    $main_url = \URL::to('/');
                    $asset_path = str_replace(str_finish(strval($main_url), '/'), '', $uri);

                    // check for external URLs. so far all the urls with current hostname
                    // has been removed. If there is a still URL which has http://---- that means
                    // its an external URL
                    $extMatch = [];
                    $extUrl = preg_match("#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|[^[:punct:]\s]|/)#", $asset_path, $extMatch );

                    if(isset($extMatch[0]))
                        continue;

                    if (isset($group['url']))
                        $config_url = $group['url'];

                    if (isset($group['remove']))
                        $config_remove = $group['remove'];

                    if ($config_remove)
                        $asset_path = str_replace(str_finish($config_remove, '/'), '', $asset_path);

                    $cdn_url = is_array($config_url) ? $config_url[array_rand($config_url)] : $config_url;
                    $output = str_replace($uri, str_finish($cdn_url, '/') . $asset_path, $output);
                }

        $response->setContent($output);
    }
    //dd($response->getOriginalContent());
    return $response;
}

}