How to serve static assets with an efficient cache policy

How to Fix the Leverage Browser Caching Warning in WordPress

serve static assets with an efficient cache policy

Add Cache-Control and Expires Headers

How to Add Cache-Control Headers in Nginx

To add Cache-Control headers in Nginx, you can add the following to your server’s configuration file:

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

How to Add Cache-Control Headers in Apache

To add Cache-Control headers if you use an Apache server, you can add the following code to your .htaccess file:

<IfModule mod_headers.c>
<FilesMatch "\.(ico|pdf|flv|swf|js|mjs|css|gif|png|jpg|jpeg|txt|woff2|woff)$">
Header set Cache-Control "max-age=31536000, public"
</FilesMatch>
</IfModule>

How to Add Expires Headers in Nginx

You can add expires headers in Nginx by adding the following to your server block:

    location ~*  \.(jpg|jpeg|gif|png|svg)$ {
        expires 365d;
    }

    location ~*  \.(pdf|css|html|js|swf)$ {
        expires 2d;
    }

How to Add Expires Headers in Apache

You can add Expires headers in Apache by adding the following to your .htaccess file

## EXPIRES HEADER CACHING ##
<IfModule mod_expires.c>
ExpiresActive On

# Images
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/webp "access plus 1 year"
ExpiresByType image/svg "access plus 1 year"

# Video
ExpiresByType video/ogg "access plus 1 year"
ExpiresByType audio/ogg "access plus 1 year"
ExpiresByType video/mp4 "access plus 1 year"
ExpiresByType video/webm "access plus 1 year"
ExpiresByType video/mpeg "access plus 1 year"

# Fonts
ExpiresByType font/ttf "access plus 1 year"
ExpiresByType font/otf "access plus 1 year"
ExpiresByType font/woff "access plus 1 year"
ExpiresByType font/woff2 "access plus 1 year"
ExpiresByType application/font-woff "access plus 1 year"

# CSS, JavaScript
ExpiresByType text/x-component "access plus 1 year"
ExpiresByType text/css "access plus 1 year"
ExpiresByType text/javascript "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType application/x-javascript "access plus 1 year"

# Others
ExpiresByType application/pdf "access plus 1 year"
ExpiresByType image/svg+xml "access plus 1 year"
ExpiresByType application/x-shockwave-flash "access plus 1 year"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresByType image/vnd.microsoft.icon "access plus 1 year"
ExpiresByType application/vnd.ms-fontobject "access plus 1 year"
ExpiresDefault "access plus 1 month"
</IfModule>
## EXPIRES HEADER CACHING ##

Related articles: