简体   繁体   中英

Enable Gzip compression and set Cache expire times in CakePHP

I am using CakePHP with Apache2. Analyzing my pages with the tool PageSpeed from Google, I find two main problems. The first is that I should enable gzipping of content, the second that I should leverage browser caching for images, javascript and css files.

I have more or less found how to remedy this, but it involves changing my main .htaccess file. This doesn't look really the CakePHP way, if nothing because that .htaccess is part of the CakePHP distribution, and I have to remember to keep it when changing version. Is there a better way to do this?

For the first, I can remedy by putting

php_value output_buffering On
php_value output_handler ob_gzhandler

I also tried

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/css text/javascript application/x-javascript
</IfModule>

but I didn't see any result with PageSpeed.

For the second I now use

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType application/x-javascript A8640000
    ExpiresByType text/javascript A8640000
    ExpiresByType text/css A8640000
    ExpiresByType image/png A8640000
</IfModule>

and it kind of works, although I still get the message "The following cacheable resources have a short freshness lifetime. Specify an expiration at least one month in the future for the following resources: blah blah"

There is no "CakePHP Way" when it comes to GZIP Compression and browser caching. This is definitely more of an Apache configuration issue. You should be able to modify the .htaccess files in your /app folder with impunity.

When updating/upgrading CakePHP, you only need to change the files in the /cake folder. You won't have to re-enable any server configurations in the .htaccess files of the /app folder, because everything there will remain the same.

Always remember: anything in the /app folder is fair game.

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
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 text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 30 days"
</IfModule>

To start mod_expires module in ubuntu run following commands

sudo a2enmod headers
sudo a2enmod expires
sudo service apache2 restart

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM