Leverage browser caching, how on apache or .htaccess?

Leverage browser caching, how on apache or .htaccess?

  1. Blog
  2. 15 November 2026
  3. 5 min read

Stefan Bogdanescu

Founder & Senior Architect

Implementing Browser Caching on Apache and .htaccess

Google's Speed Page tool frequently flags static assets like images, CSS, and JavaScript as needing "Leveraged Browser Caching." This isn't just a vanity metric; it directly impacts Time to Interactive (TTI). When a user revisits your site, the browser can serve these resources from its local disk cache rather than re-fetching them over the network. The goal is to reduce bandwidth usage and significantly speed up load times for returning visitors.

However, the implementation depends heavily on your environment. You are presented with two primary paths: modifying the main Apache configuration file (httpd.conf or apache2.conf) or using a virtual host config, versus placing directives in an .htaccess file within your document root. The source material provided illustrates a classic example of mixing these approaches, specifically enabling mod_expires.

Choosing Your Configuration Location

Before writing a single line of code, you must decide where to store your directives. This decision is not arbitrary; it dictates how Apache handles the configuration and whether those rules apply globally or just to specific directories.

If you have root access to the server (or are using Plesk/cPanel with full config control), modifying the main httpd.conf file is the preferred method for global settings. It bypasses the overhead of parsing .htaccess files, making it more performant. However, this requires a server restart or a graceful reload (systemctl reload apache2).

The alternative is using .htaccess. This is common on shared hosting where you cannot touch the main config file, or when you need to apply caching rules to specific subdirectories without reloading the entire web server. The downside is that Apache must read and parse the .htaccess file for every request, which adds a slight I/O penalty compared to compiled-in directives.

Configuring Expiration Times with mod_expires

The source material demonstrates the use of mod_expires. This module allows you to set a specific time after which a resource is considered "stale" and should be re-fetched by the browser.

A critical observation from the provided snippet is the default setting: ExpiresDefault A60. This sets every single file to expire in 60 seconds unless explicitly overridden. For a production site, this is almost certainly incorrect. You generally want static assets (images, scripts) to persist for days or weeks, while dynamic content (HTML) should expire quickly.

Here is a refined approach for an .htaccess file that addresses the specific MIME types listed in your source material but corrects the default behavior:

<IfModule mod_expires.c>
    ExpiresActive On
    
    # Default expiration for everything else (e.g., HTML, XML)
    ExpiresDefault "access plus 1 hour"
    
    # Static assets should last much longer
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/webp "access plus 1 year"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresByType text/css "access plus 1 month"
    
    # Fonts are crucial for layout and should be cached aggressively
    ExpiresByType font/woff "access plus 1 year"
    ExpiresByType font/woff2 "access plus 1 year"
</IfModule>

In this configuration, we explicitly define the cache duration for common media types. By setting ExpiresDefault to one hour, we ensure that if a new HTML page is published, visitors won't see content from an hour ago unless they have updated their browser cache manually. This is a safer default than the 60-second limit found in the example snippet, which would force re-downloads of static assets on nearly every page view.

Enabling Far-Future Caching for Performance

While mod_expires handles time-based expiration, modern performance optimization often favors "far-future" caching combined with cache validation. Instead of relying solely on a timestamp, we can set the Cache-Control header to tell browsers they don't need to check the server at all for a long period.

If you are using Apache 2.4 and have mod_headers enabled, you can combine ExpiresActive with Header:

<IfModule mod_expires.c>
    ExpiresActive On
</IfModule>
<IfModule mod_headers.c>
    Header append Cache-Control "public, max-age=31536000"
</IfModule>

This sets a maximum age of one year (31,536,000 seconds). The browser will only contact your server if the resource changes on the disk. This approach reduces the number of HTTP requests significantly compared to relying solely on ExpiresByType.

Potential Pitfalls and Best Practices

When implementing these rules, be cautious of dynamically generated content. If your HTML pages are generated by scripts (PHP, Python, etc.) inside a directory like /blog/, applying aggressive caching globally might cause users to see old posts after new ones are published.

To prevent this, you should scope your .htaccess rules to specific directories or use SetEnvIf to detect query strings that indicate dynamic requests. For example, if your site uses file-based routing where every request goes through PHP, ensure your default expiration isn't too aggressive. The source material mentions adding a Cache-Control: no-cache header for CGIs; this is still relevant. If you have a mix of static and dynamic content in the same root, consider restricting ExpiresByType to specific subdirectories using <Directory> blocks.

Finally, always test your changes. After updating your configuration, use tools like Chrome DevTools or curl to inspect the response headers. Look specifically for Cache-Control and Expires. If you see no-store or a very short max-age where you expected years, double-check that your <IfModule> blocks are actually loading and that no other rule is overriding your settings with a lower priority.

For those using Laravel or similar frameworks on Apache, remember that the web server configuration exists outside the application code. You must ensure your .htaccess rules sit correctly in your project root without conflicting with the framework's own routing rewrites. Tools like laravelcompany.com often discuss how to optimize server configurations alongside application logic, but remember that caching headers are strictly a server-side concern handled by Apache, not the PHP runtime.

Our network