Fetching resources over the network is both slow and expensive: the download may require multiple roundtrips between the client and server, which delays processing and may block rendering of page content, and also incurs data costs for the visitor. All server responses should specify a caching policy to help the client determine if and when it can reuse a previously fetched response.

To reach that goal we can apply simple code in .htaccess file which will inform the browser if the previously fetched resources can be reused. Below is a code snippet which can be placed in the .htaccess file.

<IfModule mod_headers.c>
Header set Connection keep-alive

# Cache-control headers
    # 2 HOURS
    #<filesMatch "*">
        Header set Cache-Control "max-age=7200, must-revalidate"
    #</filesMatch>

    # 2 WEEKS
    <filesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|swf)$">
        Header set Cache-Control "max-age=1209600, public"
    </filesMatch>

    # 1 DAY
    <filesMatch "\.(css)$">
        Header set Cache-Control "max-age=86400, public, must-revalidate"
    </filesMatch>

    # 2 DAYS
    <filesMatch "\.(xml|txt)$">
        Header set Cache-Control "max-age=172800, public, must-revalidate"
    </filesMatch>

    # 2 HOURS
    <filesMatch "\.(html|htm)$">
        Header set Cache-Control "max-age=7200, must-revalidate"
    </filesMatch>

    <FilesMatch "\.(gif|jpg|png|ico|css|js|pdf|txt)$">
        Header append Cache-Control "public"
    </FilesMatch>
</IfModule>

The only thing which is on your site is to set up proper expiration time for your resources. The time should be determined by the frequency of updates for each type of resources for your website.

Leverage Browser Caching – .htaccess solution
Tagged on:                         

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Social Widgets powered by AB-WebLog.com.