Tuesday, January 5, 2016

How to do Apache webserver browser caching for static files

When a URL is hit it reaches the webserver and other component and serve you  back the content.Some websites might have more static content like images ,js etc.These  files can be cached at the browser so the next hit from the same browser wont go  to the webserver and it will be served from the browser cache.To do this we need the below setup at the webserver.

Check the below module is loaded in httpd.conf

LoadModule expires_module modules/mod_expires.so 
 
You can check all the modules available in your httpd by executing 
<path to httpd>/httpd -M
 
for ex: /usr/bin/httpd -M
 
Add lines similar to below depending on your need :

<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType text/css "access plus 60 minutes"
  ExpiresByType text/javascript "access 1 year"
  ExpiresByType application/x-javascript "access plus 60 minutes"
  ExpiresByType text/xml "access plus 60 minutes"
</IfModule>
 
If module will check the module is there or not
ExpiresActive On directive will tell the http expire is on 
ExpiresByType will be used to tell which file type need to be cached in browser
 
access 1 year will keep the file type in the browser for a year,unless you clear the browser cache.
 
To check mod_expire is working or not.Hit the URL you wish from the browser.Hit it again
and check your webserver logs.You should not see the request logged in for the filetype
which is cached.
 
Or user Live http header extension for the browser to see the http header.
You will see Expires on field where it will be a future date. 

References:
Apache mod_expire


No comments:

Post a Comment

Your suggestions please