Hi,
I was interesting in how to best set cache-control
headers for a static site.
I found this thread which touches on it:
https://community.opalstack.com/d/189-setting-cache-control-or-expires-with-nginx-static-only-app/
But it's from 2020-2022 and didn't get into the specifics I needed.
I also didn't see anything in the Opalstack Documentation.
So I emailed support, received great responses (as usual), and then realized I should have posed the questions here 🤦🏻.
Below is a summary of my case and the answers from @sean and @nick.
My situation is pretty common for static sites.
I want index.html
files to never be cached and pretty much everything else to be cached far into the future. The framework I'm using (Svelte + Vite) cache-busts assets (js, css, images, etc.) via hashes in their file names.
So here's how to set cache-control
headers, for a case like this, on Opalstack and an Apache app:
1. On the Applications & Shell Users page (of the OS Dashboard), set the "Cache" setting for your app to Off
:
Setting a cache option here takes precedence over anything in an .htaccess
file (more on that below).
@sean explains some of the other options, and their values, here.
If you're ok with any of those options for all files, then set that in the Dashboard and you're done.
But if you want a mix of cache headers, for different file types, you'll need to first set this to Off
.
@sean: The cache setting in the control panel creates headers which are applied in our front-end Nginx proxy and cannot be overridden on the back end with .htaccess.
If you want granular control over caching on the back end, then do not use the cache setting in the control panel, instead use an Apache app and configure the caching with .htaccess.
2. Add the following directives to the .htaccess
file in the root of your app (adjust as necessary):
<IfModule mod_headers.c>
# No caching for `.html` and `.php` files
<FilesMatch "\.(html|php)$">
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "0"
</FilesMatch>
# Heavily cache all other assets
<FilesMatch "\.(jpg|jpeg|gif|png|css|js|woff2|woff|eot|ttf|otf)$">
Header set Cache-Control "public, max-age=31536000, immutable"
</FilesMatch>
</IfModule>
(I found some alternate versions using mod_expires.c
, but those don't work on OS.)
You can confirm these via curl -I
or your browser's DevTools.
I hope this helps.