Enable Leverage Browser Caching on Apache and Nginx

What is leverage brwoser caching ?

Everytime User open website, It has to download all the content/web files from server to properly render/display the webpage. It inclues all css,js, images etc.

Some of the webpage may contain only few small sized files, But some could have large number of big sized files and these larged size files take time to download from server. It leads to slowness of website.

Leverage Browser Caching can help you to overcome this issue, It stored these files in browser cache and then if user visit website after first time or refresh page agaiin or go to anyother page of website, it will not download these css, js and images. It will pick them from local caching directory, instead of downloading from server. Hense It affect website speed and performance

How to enable leverage browser Caching on Apache ?

To enable leverage browser caching we need to add following code to .htaccess file exists in root directory of your website.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
	# Turn on the module.
	ExpiresActive on
	# Set the default expiry times.
	ExpiresDefault "access plus 2 days"
	ExpiresByType image/jpg "access plus 1 month"
	ExpiresByType image/gif "access plus 1 month"
	ExpiresByType image/jpeg "access plus 1 month"
	ExpiresByType image/png "access plus 1 month"
	ExpiresByType text/css "access plus 1 month"
	ExpiresByType text/javascript "access plus 1 month"
	ExpiresByType application/javascript "access plus 1 month"
	ExpiresByType application/x-shockwave-flash "access plus 1 month"
	ExpiresByType text/css "now plus 1 month"
	ExpiresByType image/ico "access plus 1 month"
	ExpiresByType image/x-icon "access plus 1 month"
	ExpiresByType text/html "access plus 600 seconds"

If above code doesn’t work we’ll need to check if apache mod_expire module is enable and installed on server.

How to enable leverage Browser Caching on Nginx

To enable leverage brwoser caching on nginx will not work like apache, To enable leverage caching on nginx, we need to modify website configuration file for nginx. Usually you will find the file in /etc/nginx/sites-available/{doaminname}.com.conf. You need to put following code in that file inside server brackets

1
2
3
4
5
location ~*  \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 365d;
    }location ~*  \.(pdf)$ {
        expires 30d;
}

after making changes you need to restart nginx server.

 

sudo /etc/init.d/nginx restart

or

sudo service nginx restart
Comments
  1. Pat

Leave a Reply

Your email address will not be published. Required fields are marked *

*


Skip to toolbar