简体   繁体   中英

How to use HTTP caching in nginx for html files?

My current nginx configuration for HTTP content caching is something like this:

location ~* \.html$ {
    expires -1;
}

location ~* \.(css|js|gif|jpe?g|png)$ {
    expires 168h;
    add_header Pragma public;
    add_header Cache-Control "public, must-revalidate, proxy-revalidate";
}

As you see I've disabled caching on the HTML files since they get updated quite frequently. Now I want to update my configuration with HTML caching enabled by using a script to rename the parent directory of my html files. From:

view/*.htmls

To

view/randomString/*.htmls

So, basically what's happening is all my html files will be moved to a directory with random name, that will be generated during each deployment of the web-app. Is it the right approach? Or there is already a better way to achieve this?

To get a good grasp on how HTTP caching works. It's a good idea to read that section of the RFC .

Instead of changing all the urls with every single release and breaking all bookmarks people may have made, you could give Entity Tag Cache Validators (or ETags ) a try. You can have nginx create etags for your html files. Al you have to do to have nginx regenerate them is change the timestamp by touch ing all files you changed.

PS if you run a really really busy thing, and want to avoid the requests that ETags do for checking them. You can set a long expire date like you have for your other files and change the urls by appending ?randomstring to urls, like is explained in Cache busting via params

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM