cmc/cleberg.net

My personal web garden & blog.

clone: git clone https://gitbay.org/cmc/cleberg.net.git

main: content/blog/2022-02-20-nginx-caching.org · raw

 1#+date:        [2022-02-20 Sun 00:00:00]
 2#+title:       Nginx Caching for Static Content
 3#+description: Configuring Nginx to cache static assets like CSS, JS, and images.
 4#+slug:        nginx-caching
 5#+filetags:    :linux:web:
 6
 7* Update Your Nginx Config to Cache Static Files
 8
 9If you run a website on Nginx that serves static content (i.e., content that is
10not dynamic and changing with interactions from the user), you would likely
11benefit from caching that content on the client-side. If you're used to Apache
12and looking for the Nginx equivalent, this post should help.
13
14Luckily, setting up the cache is as easy as identifying the file types you want
15to cache and determining the expiration length. To include more file types,
16simply use the bar separator (=|=) and type the new file extension you want to
17include.
18
19#+begin_src config
20server {
21    ...
22
23    location ~** .(css|js|jpg|jpeg|gif|png|ico)$ {
24        expires 30d;
25    }
26
27    ...
28}
29#+end_src
30
31I have seen some people who prefer to set =expires= as =365d= or even =max=, but
32that is only for stable, infrequently changing websites. As my site often
33changes (i.e., I'm never content with my website), I need to know that my
34readers are seeing the new content without waiting too long.
35
36So, I went ahead and set the expiration date at =30d=, which is short enough to
37refresh for readers but long enough that clients/browsers won't be re-requesting
38the static files too often, hopefully resulting in faster loading times, as
39images should be the only thing slowing down my site.
40
41* Testing Results
42
43To test my changes to the Nginx configuration, I used the [[https://addons.mozilla.org/en-US/firefox/addon/http-header-live/][HTTP Header Live]]
44extension on my Gecko browser and used the sidebar to inspect the headers of a
45recent image from my blog.
46
47In the image below, you can see that the =Cache-Control= header is now present
48and set to 2592000, which is 30 days represented in seconds (30 days _ 24
49hours/day _ 60 minutes/hour ** 60 seconds/minute = 2,592,000 seconds).
50
51The =Expires= field is now showing 22 March 2022, which is 30 days from the day
52of this post, 20 February 2022.
53
54* Caveats
55
56Remember that this caching system is *client-side*, which means that content is
57only cached for as long as a client allows it. For example, my browser purges
58all caches, data, etc. upon exit, so this caching policy will only work as long
59as my browser remains open and running.
60
61If you need to test updates to your site, you'll need to clear the cache to see
62updates for any file extension you configured. This can often be done with the
63=Shift + F5= or =Ctrl + F5= key combinations in most browsers.