antonputra / tutorials

DevOps Tutorials
https://youtube.com/antonputra
MIT License
3.19k stars 2.5k forks source link

Add Cache-Control headers for static content #338

Closed melroy89 closed 2 weeks ago

melroy89 commented 2 weeks ago

When we are talking about static data in general (especially when serving a static site). A lot can be optimized by introducing caches on the correct request paths for the client (browser) to cache content.

In this PR, I add Cache-Control headers for Nginx (for 25 days on static content). Assuming the application itself doesn't set any headers.
On static files I normally also do not add access logs. So under Nginx I also add access_log off; for this static location/files (it's up to you to disable access log on static files).

Changes are:


The same caching setup for Apache2 it is something like this:


<FilesMatch "\.(?:css(\.map)?|js(\.map)?|jpe?g|png|tgz|gz|rar|bz2|doc|pdf|ptt|tar|gif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|mpe?g|avi|ogv|flv|wmv|svgz?|ttf|ttc|otf|eot|woff2?)$">
  Header set Cache-Control "max-age=2160000, public, no-transform"
  Header unset Last-Modified
  Header unset ETag
</FilesMatch>

And for Caddy it is something like this:

{
...

    @staticFiles {
        path_regexp \.(?:css(\.map)?|js(\.map)?|jpe?g|png|tgz|gz|rar|bz2|doc|pdf|ptt|tar|gif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|mpe?g|avi|ogv|flv|wmv|svgz?|ttf|ttc|otf|eot|woff2?)$
    }

    header @staticFiles {
        Cache-Control "max-age=2160000, public, no-transform"
    }
}
melroy89 commented 2 weeks ago

thanks! it may be practical, but it won't play a role in the test unless i use something like selenium to test it

It might be useful for future tests..