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.
4. Use Output Buffering
For dynamically generated content, you can use output buffering in PHP to control caching more effectively.
<?php
// 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');
?>
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.
Post a Comment
0Comments