Optimizing the loading speed of front-end resources is crucial when building high-performance websites or web applications. An effective method is to use the HTTP caching mechanism to reduce network requests, reduce server load, and improve user experience by caching static resources. This article will introduce how to configure front-end HTTP cache using Nginx to speed up the loading speed of your website.
What is HTTP Cache?
HTTP caching is a mechanism for caching HTTP responses between the client (browser) and the server. When the browser first requests a resource, the server returns a response and includes a cache instruction in the response. These cache directives tell the browser how to handle the resource and when to request it again.
Nginx cache basics
In Nginx, cache is configured through proxy_cache_path and proxy_cache instructions. proxy_cache_path defines the cached storage path and related parameters, while proxy_cache directive is used to specify which requests should be cached.
Cache mechanism in Nginx
Nginx provides two main caching mechanisms: proxy cache and browser cache. Proxy cache refers to Nginx as a proxy server that stores the requested response in its own cache. When the same request is received again, the response can be provided directly from the cache. The browser cache indicates that the browser stores the resource copy by setting the HTTP response header.
Configure Nginx to implement front-end HTTP cache
server { #Other configuration items... location ~* .(html)$ { access_log off; add_header Cache-Control max-age=no-cache; } location ~* .(css|js|png|jpg|jpeg|gif|gz|svg|mp4|ogg|ogv|webm|htc|xml|woff)$ { access_log off; add_header Cache-Control max-age=360000; } #Configuration of other resource types...}
In the above configuration, we use the location directive combined with regular expressions to match different types of resources. For resources ending in .html, we set the Cache-Control header to max-age=no-cache, which tells the browser not to cache the resource. For resources ending with .css, .js, .png, etc., we set the Cache-Control header to max-age=360000, which means that the browser can cache the resource and request it again after 360000 seconds (about 100 hours).
Through such a configuration, the caching strategy can be flexibly controlled according to different resource types to meet the needs of the website.
The following is analyzing these two parameters in Cache-Control:
add_header Cache-Control max-age=no-cache;Meaning of : The html file does not set a forced cache time, negotiates cache, and uses Last-Modified. no-cache initiates a round trip communication to verify the cached response, but if the resource has not changed, it will not be downloaded, and returns 304.
add_header Cache-Control max-age=360000;The meaning of sets a forced cache for the file with the suffix above, and the cache time is 360,000 seconds. When you access it for the first time, you request it from the server. When the browser is refreshed again except for the first time, it will be read from the browser cache. Then the forced cache is generally read from the memory first, and if the memory does not exist, then read from the hard disk.
Selection of cache time
The choice of cache time depends on the frequency of the resource being updated. For resources that do not change frequently, such as library files or icons, a longer cache time can be set. For resources that are frequently updated, such as HTML pages, it may be necessary to set a short cache time or not.
3 properties about Cache in the browser:
1. Cache-Control:
Set the relative expiration time, max-age indicates the cache time in seconds. If the static resources are cached only once, the value of max-age can be set to 31536000000 (10,000 years). For example, for submitted orders, in order to prevent the browser from falling back and resubmitting, you can use the no-store of Cache-Control to absolutely prohibit cache. Even if the browser rolls back, it still requests the server, and then judges the status of the order and gives corresponding prompt information!
Common values of cache-control of Http protocol and their combination definitions:
no-cache: The data content cannot be cached. The server is revisited every time the request is requested. If there is max-age, the server will not be accessed during the cache.
no-store: Not only can it not be cached, but it cannot even be stored temporarily (that is, the resource cannot be stored temporarily in a temporary folder).
private (default): can only be cached in the browser, and the server is only accessible on the first request. If there is max-age, the server will not be accessed during the cache.
public: It can be cached by any cache area, such as: browser, server, proxy server, etc.
max-age: relative expiration time, that is, cache time in seconds.
no-cache, private: Re-access the server when opening a new window. If max-age is set, no server will be accessed during the cache.
- private, positive max-age: The server will not be accessed during backing.
- no-cache, positive max-age: The server will be accessed when backing.
2. Expires:
Set the absolute expiration time in minutes, the priority is lower than Cache-Control, and the latter is effective when both Expires and Cache-Control are set. That is to say, one thing to note: Cache-Control has higher priority than Expires
Expires plays a role in controlling page cache. Proper configuration of expires can reduce many server requests. Expires can be configured in the http segment, the server segment or the location segment. For example, the expiration time of controlling pictures is 30 days, which can be configured as follows:
location ~ .(gif|jpg|jpeg|png|bmp|ico)$ { root /var/www/img/`;` expires 30d; } For example: location ~ .(wma|wmv|asf|mp3|mmf|zip|rar|swf|flv)$ { root /var/www/upload/`;` expires max; }
3. Last-Modified:
The last modification time of this resource is, the next time the browser requests the resource, the browser will first send a request to the server, and attach the If-Unmodified-Since header to explain the last modification time of the resource cached by the browser. If the server finds that there is no modification, it will directly return 304 (Not Modified) response information to the browser (very little content). If the server finds that the time has been modified, the requested resource will be returned as usual.
Need to note:
- The Last-Modified property is usually used in conjunction with the Expires or Cache-Control property, because even if the browser sets the cache, when the user clicks the "Refresh" button, the browser ignores the cache and continues to send requests to the server. At this time, Last-Modified will be able to reduce the response overhead well.
- ETag will return a resource ID to the browser. If there is a new version, it will be sent normally and attached with a new ID. Otherwise, it will return 304. However, in the case of server cluster, each server will return a different ID, so ETag is not recommended.
The client browser cache described above refers to the storage location in the client browser, but the actual setting of the client browser cache is done in the resources on the server. Although the above mentioned properties about the client browser cache, the setting of these properties actually requires setting in the server resources. There are usually two operating methods to set the browser cache, one is set through the page instruction declaration, and the other is set through programmatic means.
Here are a few simple configurations for setting Cache-Control header information on the related page:
Example 1:
if ($request_uri ~* "^/$|^/search/.+/|^/company/.+/"`) {` add_header Cache-Control max-age=3600; }
The max-age I understand means: the client's local cache is directly used by the client within the configured survival time, and the client can retrieve new data from the server after the survival time. Of course, these also depend on the settings of the client browser.
Example 2:
location ~ .*.(css|js|swf|php|htm|html )$ { add_header Cache-Control no-store; }
Example 3:
location ~ .*.(js|css)$ { expires 10d; }
Example 4: Add no-cache to the request ending of html
location / { access_log /data/nginx/log/xxx`.log api;` root /home/www/html`;` if ($request_filename ~ .*.(htm|html)$) { add_header Cache-Control no-cache; } }
Things to note
Make sure the cache policy does not apply to all resources. For example, for user personal information or dynamic content, it should always be set to not cache.
Using ETag or Last-Modified headers can further improve caching efficiency, which can help the browser recognize the update of resources.
in conclusion
By rationally configuring Nginx's client caching strategy, we can effectively improve the loading speed of front-end resources, reduce server load, and thus improve the performance of the entire web application, which can significantly improve the performance and user experience of the web application. When configuring cache, we need to adjust the cache time according to the frequency and importance of the resource update, ensuring that users always get the latest content, while reducing unnecessary server requests. Through meticulous configuration and optimization, Nginx can become a powerful tool to improve the performance of web applications.
This is the article about Ningx configuration front-end http cache implementation. For more information about Ningx configuration http cache, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!