htaccess Header set Cache-Control

htaccess Header set Cache-Control
htaccess Header set Cache-Control

Learn how to configure Cache-Control headers in your htaccess file to improve website performance by setting cache durations for images, CSS, and JavaScript files.

Your visitors shouldn’t re-download the same logo on every page. Once their browser has it, let it keep it. That’s what the Cache-Control header does, and you can set it straight from your .htaccess file.

Here’s how to cache your static files (images, CSS, JavaScript) so returning visitors load them from disk instead of hitting your server again.

The max-age value

What it means

max-age is how long (in seconds) the browser treats a file as fresh before it asks your server for a new copy. Longer means fewer requests and faster repeat visits.

A few common values:

  • One hour: max-age=3600
  • One day: max-age=86400
  • One week: max-age=604800
  • One month: max-age=2628000
  • One year: max-age=31536000

The examples below use one year (31536000) for images, CSS, and JS. Change the number to whatever suits your site.

The .htaccess rules

Open the .htaccess file in the root of your WordPress install and add this:

HTML
# Set One year for image files
<filesMatch ".(jpg|jpeg|png|gif|ico)$">
Header set Cache-Control "max-age=31536000, public"
</filesMatch>
# Set One year for CSS and Javascript
<filesMatch ".(css|js)$">
Header set Cache-Control "max-age=31536000, public"
</filesMatch>
What each piece does
  • filesMatch: matches files by type. The first block targets images (JPG, PNG, GIF, ICO), the second targets CSS and JS.
  • Header set Cache-Control: writes the header on those files. max-age=31536000 tells the browser to hold them for a year.
  • public: allows shared caches (CDNs, proxies) to store the file too, not just the visitor’s browser.
The catch with long caching

A one-year cache is great for performance and a problem the day you edit a file. The browser won’t ask for the new version until the year is up, so your visitors keep seeing the old one.

Fix it by changing the filename whenever the content changes. A fingerprinted name like style.a1b2c3.css is the reliable way, since the browser sees a brand new URL and fetches it. A query string like style.css?v=1.0 often works too, but some CDNs ignore the query string when caching, so it’s less dependable. Most build tools and caching plugins handle this fingerprinting for you.

For HTML that changes often, don’t set a long max-age at all. Keep it short or skip it so pages stay current.

One requirement

Header set comes from Apache’s mod_headers module. Most hosts enable it by default. If the header doesn’t show up, that module is likely off, so ask your host to turn it on. And this is an Apache trick: on Nginx you’d set caching in the server config instead.

Next: Enable Gzip Compression via htaccess

Leave a Comment

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


Scroll to Top