How to enable browser caching on the server

In this post you can find different ways to enable browse caching on the server with PHP or using Apache htaccess file or Nginx ...

Home Programming Examples Other Examples → How to enable browser caching on the server
how to enable browser caching on the server


Browser caching allows frequently accessed resources (such as images, stylesheets, and scripts) to be stored locally on the user's device. Subsequent visits to your site can then load these resources from the local cache, reducing the need to download them again from the server. This leads to faster page load times.
Caching static resources on the user's device also reduces the amount of data that needs to be transferred between the server and the client. This can result in significant bandwidth savings, which is especially beneficial for users on limited or slow internet connections.

You can find below information on enabling browser caching with PHP and also using .htaccess file on Apache or also nginx.

With PHP to instruct the browser to cache a resource for a specific duration, you can set the appropriate HTTP headers in your PHP script. Specifically, you'll want to use the Cache-Control header to define the maximum age of the cache, and the Expires header to set an expiration time. Here's an example of how you can set these headers to instruct the browser to cache a resource for 4 hours:


header('Cache-Control: max-age=14400');
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 14400) . ' GMT');


In this example we use 4 hours or 4*3600 seconds = 14400 , but you can also set any other time you prefer.

The same can be achieved also on Apache by adding in the .htaccess the following line -


Header set Cache-Control "max-age=14400, public"


To use that, it's necessary to have the mod_headers module enabled on your server. If it's not enabled, you can usually enable it using the following command:


a2enmod headers


And finally if you use nginx and would like to enable caching of all image, js and css files for 4 hours, you can add to your nginx configuration file


location ~* .(js|css|png|jpg|jpeg|gif|ico)$ {
expires 4h;
add_header Cache-Control "public, no-transform";
}




See More ExamplesHire Me For A Project






 
Connect with meLinkedIn ProfileFacebook Profile


2024 © SofiaCoder.com
×

Programming ExamplesPHP ExamplesMySQL ExamplesJavaScript ExamplesHTML ExamplesCSS ExamplesNode.js ExamplesOther Home PageSofia Coder LinkedIn ProfileSofia Coder Facebook Profile