2016-04-18 79 views
0

我需要添加新的規則.htaccess或將代碼添加到YII2的index.php?如何爲yii2啓用gzip?

我的網站在共享主辦。

我只想壓縮.css和.js文件。我不想壓縮所有響應。

回答

1

您可以通過在index.php中的yii \ web \ Response上附加事件處理程序來使其工作。

$application = new yii\web\Application($config); 
$application->on(yii\web\Application::EVENT_BEFORE_REQUEST, function(yii\base\Event $event){ 
    $event->sender->response->on(yii\web\Response::EVENT_BEFORE_SEND, function($e){ 
     ob_start("ob_gzhandler"); 
    }); 
    $event->sender->response->on(yii\web\Response::EVENT_AFTER_SEND, function($e){ 
     ob_end_flush(); 
    }); 
}); 
$application->run(); 
0

我添加了以下規則爲.htaccess:

<IfModule mod_filter.c> 
    AddOutputFilterByType DEFLATE "application/atom+xml" \ 
            "application/javascript" \ 
            "application/json" \ 
            "application/ld+json" \ 
            "application/manifest+json" \ 
            "application/rdf+xml" \ 
            "application/rss+xml" \ 
            "application/schema+json" \ 
            "application/vnd.geo+json" \ 
            "application/vnd.ms-fontobject" \ 
            "application/x-font-ttf" \ 
            "application/x-javascript" \ 
            "application/x-web-app-manifest+json" \ 
            "application/xhtml+xml" \ 
            "application/xml" \ 
            "font/eot" \ 
            "font/opentype" \ 
            "image/bmp" \ 
            "image/svg+xml" \ 
            "image/vnd.microsoft.icon" \ 
            "image/x-icon" \ 
            "text/cache-manifest" \ 
            "text/css" \ 
            "text/html" \ 
            "text/javascript" \ 
            "text/plain" \ 
            "text/vcard" \ 
            "text/vnd.rim.location.xloc" \ 
            "text/vtt" \ 
            "text/x-component" \ 
            "text/x-cross-domain-policy" \ 
            "text/xml" 

</IfModule> 

配置清單:https://github.com/h5bp/server-configs