gb5256
gb5256

Reputation: 191

Yii2 Asset Bundle: How to set headers?

I am using Asset Bundles of yii2. But I do not find a away to influence the http header of each file (css and js). For example I want to set the cache. For the controllers I do this:

'class' => 'yii\filters\HttpCache', 
            'only' => ['index', 'view'],
            'cacheControlHeader' => 'public, max-age=3600',
            'lastModified' => function ($action, $params) {
                $q = new \yii\db\Query();
                return $q->from('user')->max('updated_at');
            },

But how to do this for the Assets / Asset Bundles?

Upvotes: 3

Views: 1580

Answers (3)

Tuychiev Toir
Tuychiev Toir

Reputation: 370

class PostController extends Controller
{
    public function behaviors()
    {
        return [
            [
                'class'      => 'yii\filters\PageCache',
                'only'       => ['view', 'short'],      // actions
                'duration'   => 60,
                'enabled'    => !YII_DEBUG,
                'variations' => [
                    HTTPS_ON,
                    $_SERVER['SERVER_NAME'],
                 ]
            ]
       ];
   }
  ...

or documentation this url https://www.yiiframework.com/doc/api/2.0/yii-filters-pagecache

Upvotes: 0

Chloe
Chloe

Reputation: 26274

Put this into a .htaccess file in your web/ folder to set Expires headers to cache JS, CSS, images, etc.

## EXPIRES CACHING ##
<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresDefault "access plus 1 month"
  #ExpiresByType image/jpg "access plus 1 year"
  #ExpiresByType image/jpeg "access plus 1 year"
  #ExpiresByType image/gif "access plus 1 year"
  #ExpiresByType image/png "access plus 1 year"
  #ExpiresByType text/css "access plus 1 month"
  #ExpiresByType application/pdf "access plus 1 month"
  #ExpiresByType application/javascript "access plus 1 month"
  #ExpiresByType text/javascript "access plus 1 month"
  #ExpiresByType text/x-javascript "access plus 1 month"
  #ExpiresByType application/x-shockwave-flash "access plus 1 month"
  #ExpiresByType image/x-icon "access plus 1 week"
</IfModule>

Upvotes: 1

Beowulfenator
Beowulfenator

Reputation: 2300

You can't really do that.

Your CSS and JS files are being served by your web server (whichever one you're using). Assets and bundles are a mechanism that takes files from a folder not accessible by web server (e.g. /assets/), and places them into a folder accessible by web server, like /web/assets/xxxxxxx, which is then visible via http://<your_domain>/assets/xxxxxxx.

The files are served directly without any involvement from Yii. So if you need specific headers (for cache control or any other reason), your web server config is where it should be done.

Upvotes: 1

Related Questions