Serve static assets with an efficient cache policy

Jyotishgher Astrology
By -
0

 Serve static assets with an efficient cache policy

To implement a long cache lifetime on a PHP website, you can set HTTP headers that instruct the browser to cache certain types of content for a specified period. This helps speed up repeat visits as the browser can load the cached content instead of fetching it from the server again.

Serve static assets with an efficient cache policy


Here are the steps to set up long cache lifetimes for static resources like images, CSS, JavaScript, and other assets on a PHP website:

1. Configure Cache-Control Headers in PHP

Add the following code to your PHP files or create a common include file that sets the headers for all your pages. This will set the Cache-Control and Expires headers for caching.


<?php

// Set cache expiration to 1 year in the future

$expires = 60*60*24*365; // 1 year in seconds


header("Cache-Control: public, max-age=$expires");

header("Expires: " . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT');

?>


2. Set Cache-Control Headers in Your Web Server Configuration

For Apache:

  • Open your .htaccess file or your main server configuration file and add the following lines to set long cache lifetimes for different types of static content.
<IfModule mod_expires.c>
    ExpiresActive On

    # Images
    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 image/webp "access plus 1 year"

    # CSS and JavaScript
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresByType text/javascript "access plus 1 month"

    # Video
    ExpiresByType video/mp4 "access plus 1 year"
    ExpiresByType video/webm "access plus 1 year"

    # Web fonts
    ExpiresByType application/font-woff2 "access plus 1 year"
    ExpiresByType application/font-woff "access plus 1 year"
</IfModule>

4. Use Output Buffering

For dynamically generated content, you can use output buffering in PHP to control caching more effectively.


<?php

ob_start();


// Your PHP code here


$expires = 60*60*24*365; // 1 year in seconds

header("Cache-Control: public, max-age=$expires");

header("Expires: " . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT');


ob_end_flush();

?>


Summary

By setting long cache lifetimes, you can significantly improve the performance of repeat visits to your PHP website. Configure your server to send appropriate cache headers for static content, use versioning for static files, and manage cache headers for dynamically generated content using PHP. This ensures that your website remains fast and responsive for returning users.

Tags:

Post a Comment

0Comments

Post a Comment (0)