如何仅缓存静态资源,禁止特定页面HTML缓存?
Hey there! Let's get your caching setup right so your HTML pages always reload when users revisit, while your static assets (CSS, JS, images, etc.) stay cached to save bandwidth and load faster.
First, Let's Fix Your Updated .htaccess Issues
Your current updated config has a couple of syntax problems that are probably causing it to not work as expected:
- The
<If>directive uses an incorrectfilesMatchsyntax inside the condition - You've added unnecessary equals signs (
=) in yourHeader setlines, which breaks Apache's syntax
Correct .htaccess Configuration
Here's the properly formatted config that will do exactly what you want:
# Cache static assets for 30 days (2592000 seconds) <FilesMatch "\.(css|jpg|jpeg|png|gif|js|ico|woff)$"> Header set Cache-Control "max-age=2592000, public" </FilesMatch> # Disable caching for all other files (including HTML) <FilesMatch "^\.(?!css|jpg|jpeg|png|gif|js|ico|woff$)"> Header set Cache-Control "no-cache, no-store, must-revalidate" Header set Pragma "no-cache" Header set Expires "Fri, 01 Jan 1990 00:00:00 GMT" </FilesMatch>
How This Works
Let's break down each part:
- Static Assets: The first
<FilesMatch>targets all your specified file types. Themax-age=2592000tells browsers and proxies to cache these files for 30 days, andpublicallows shared caches (like CDNs or ISPs) to store them too. - HTML & Non-Static Files: The second
<FilesMatch>uses a negative lookahead (^\.(?!...)) to target every file that isn't in the static asset list. The headers here:no-cachetells browsers to revalidate with the server before using any cached copyno-storeprevents browsers from saving any cached version at allmust-revalidateenforces that expired caches can't be used without checking the serverExpiressets a past date to immediately mark the content as stalePragmais a legacy header for older browsers that still respect it
Alternative Approach Using and
If you prefer using <If>/<Else> instead of multiple <FilesMatch> blocks, here's the correct syntax for that:
<If "%{REQUEST_FILENAME} =~ /\.(css|jpg|jpeg|png|gif|js|ico|woff)$/"> Header set Cache-Control "max-age=2592000, public" </If> <Else> Header set Cache-Control "no-cache, no-store, must-revalidate" Header set Pragma "no-cache" Header set Expires "Fri, 01 Jan 1990 00:00:00 GMT" </Else>
Note: This uses Apache's expression syntax with %{REQUEST_FILENAME} to match the file extension, which is the correct way to use conditions in <If> directives.
Bonus Tip for Static Asset Updates
To make sure users get the latest version of your static assets when you update them, add a version hash or number to the filename (e.g., style.abc123.css instead of style.css). This bypasses the cache automatically because the filename is new, so browsers will download the updated file immediately.
内容的提问来源于stack exchange,提问作者Cannon Moyer

