.htaccess recipes
.htaccess files are directory-level configuration files for the Apache server that supplement its global configuration file (e.g. httpd.conf).
Caching
For static files, the ETag response header is set with the FileETag directive. To configure it to the file’s content hash:
FileETag Digest
Gotcha: Etags don’t work well with gzipped content in Apache, preventing the server from ever returning HTTP 304 Not Modified status code for conditional requests sending a
If-None-Matchheader value with a-gzipsuffix. See theDeflateAlterETagdirective, introduced in v2.4.58 (October 2023), for possible solutions. Be advised that you may not be able to configureDeflateAlterETagfrom.htaccessfiles on a shared hosting plan, in which case you’ll have to disable either etags or gzip.
Apache has the convenient mod_expires module for setting the Expires response header, but this header has been superseded by the more powerful Cache-Control header, which is handled by the mod_headers module.
<IfModule mod_headers.c>
Header set Cache-Control no-cache, max-age=0
<FilesMatch ".+\.(gif|jpe?g|png|avif|webp|svg|mp4|webm|woff2?)$">
Header set Cache-Control max-age=…
</FilesMatch>
</IfModule>
To match files from a specific directory, you must place a
.htaccessfile in that directory, as theFilesMatchconstruct only matches the filename.
See also: Apache’s Caching Guide
Redirects
For an example, see HTTP 301 redirects in Eleventy.
Further reading
- Apache configuration:
.htaccesson MDN.