Home > Article > Operation and Maintenance > Nginx cache cleaning configuration, optimize website static resource update
Nginx cache cleaning configuration, optimize website static resource update
Introduction:
During the website development process, there are often updates to static resources, such as CSS, JavaScript, and images. However, due to the browser's caching mechanism, visitors may not be able to immediately obtain the latest version of the static resource. In order to solve this problem, we can use Nginx for cache cleaning configuration to optimize the update of website static resources.
1. Nginx cache configuration
First, we need to add the following instructions to the Nginx configuration file nginx.conf to configure cache-related settings:
http { ... proxy_cache_path /path/to/cache levels=1:2 keys_zone=cache_zone:10m max_size=10g inactive=60m; ... server { ... location ~* .(css|js|png|jpg|jpeg|gif|ico)$ { expires 30d; add_header Pragma public; add_header Cache-Control "public"; proxy_cache cache_zone; proxy_cache_key $scheme$proxy_host$uri$is_args$args; proxy_cache_valid 200 301 302 404 1d; } ... } ... }
2. Nginx cache cleaning configuration
When we update the static resource files of the website, we need to clear the old version files in the cache so that visitors can obtain the latest static resources. . In order to achieve this, we can add the following code to the Nginx configuration file:
http { ... proxy_cache_path /path/to/cache levels=1:2 keys_zone=cache_zone:10m max_size=10g inactive=60m; ... server { ... location /purge-cache { internal; proxy_cache_purge cache_zone "$scheme$proxy_host$uri$is_args$args"; } ... } ... }
3. Code Example
Assuming that the CSS file in our website is located at http://example.com/static/css/style.css, we can use the following code to clear the cache. This file:
curl -X PURGE http://example.com/purge-cache/static/css/style.css
This request will cause nginx to clear the cache file corresponding to the URL in the cache, and the cache will be regenerated the next time the URL is accessed.
Conclusion:
By configuring Nginx cache cleaning, we can optimize the update of static resources on the website. When we update static resources, we only need to send a request to clear the cache, so that visitors can obtain the latest resource files and improve website performance and user experience.
Reference materials:
The above is the detailed content of Nginx cache cleaning configuration, optimize website static resource update. For more information, please follow other related articles on the PHP Chinese website!