Home > Operation and Maintenance > Nginx > How to configure Nginx content cache and what are the common parameter configurations

How to configure Nginx content cache and what are the common parameter configurations

WBOY
Release: 2023-05-11 22:25:11
forward
1613 people have browsed it

Usage scenario:

The project page needs to load a lot of data, which does not change frequently. It does not involve personalized customization. Data is dynamically generated for each request, and the performance is not good. Cache the results based on the request route and parameters. Using nginx cache will greatly improve the request speed.

Basics

You only need to configure proxy_cache_path and proxy_cache to enable content caching. The former is used to set the cache path and configuration, and the latter is used to enable caching. .

http {
 ...
 proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;

 server {
 proxy_cache mycache;
 location / {
  proxy_pass http://localhost:8000;
 }
 }
}
Copy after login

Corresponding parameter description:

1. The local disk directory used for caching is/path/to/cache/

2 .levels sets a two-level directory hierarchy at /path/to/cache/. Placing a large number of files in a single directory can result in slow file access, so for most deployments we recommend a two-level directory hierarchy. If the levels parameter is not configured, nginx will put all files in the same directory.

3.keys_zone Set up a shared memory area, which is used to store cache keys and metadata, somewhat similar to the use of timers. Putting a copy of the key into memory allows nginx to quickly decide whether a request is a hit or a miss without retrieving the disk, which greatly improves retrieval speed. A 1MB memory space can store approximately 8,000 keys, so the 10MB memory space configured above can store almost 80,000 keys.

4.max_size sets the upper limit of the cache (10g in the above example). This is optional; not specifying a value allows the cache to grow and consume all available disk space. When the cache reaches this limit, the processor calls the cache manager to remove the least recently used files, thus reducing the cache space to below this limit.

5.inactive specifies the time the item can remain in memory without being accessed. In the example above, if a file is not requested within 60 minutes, cache management will automatically delete it from memory, regardless of whether the file has expired. The default value of this parameter is 10 minutes (10m). Note that inactive content is different from expired content. nginx will not automatically delete expired content specified by the cache control header (cache-control:max-age=120 in this example). Expired content will only be deleted if it is not accessed within the time specified by inactive. If expired content is accessed, nginx will refresh it from the original server and update the corresponding inactive timer.

6.nginx will initially put the files destined to be written to the cache into a temporary storage area. The use_temp_path=off command instructs nginx to write these files to the same directory when caching them. We strongly recommend that you set the parameter to off to avoid unnecessary data copies in the file system. use_temp_path was introduced in nginx1.7 version and nginx plus r6.

Eventually, the proxy_cache command starts caching content whose url matches the location part (in this case, /). You can also add the proxy_cache command to the server section, which will apply caching to all services whose locations do not specify their own proxy_cache command.

nginx cache-related processes

There are two additional nginx processes involved in the cache:

  • cache manager Started periodically to check cache status. If the cache size exceeds the limit set by the max_size parameter in proxy_cache_path, the cache manager deletes recently accessed data. Between cache manager starts, the amount of cached data may briefly exceed the configured size.

  • cache loader only runs once, after nginx starts. It loads metadata about previously cached data into a shared memory area. Loading the entire cache at once may consume enough resources to degrade nginx's performance in the first few minutes after startup. To avoid this, configure iterative loading of the cache by including the following parameters in the proxy_cache_path directive:

    • loader_threshold - iteration duration in milliseconds (default Next 200)

    • loader_files - Maximum number of items loaded during one iteration (default 100)

    • loader_sleeps - Delay between iterations , in milliseconds (50 by default)

In the following example, the iteration lasts for 300 milliseconds or until 200 items are loaded:

proxy_cache_path /data/nginx/cache keys_zone=one:10m loader_threshold=300 loader_files=200;
Copy after login

Other commonly used parameters

Configuration example:

proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;

server {
 ...
 location / {
  proxy_cache my_cache;
  # proxy_cache_key "$host$request_uri$cookie_user";   proxy_cache_min_uses 3;
  proxy_cache_methods get head post;
  proxy_cache_valid 200 302 10m;
  proxy_cache_valid 404  1m;
  # proxy_cache_valid any 5m;   proxy_pass http://localhost:8000;
 }
}
Copy after login

Corresponding parameter description:

  • ##proxy_cache_key In order to change the request characteristics used when calculating the key, specify the cached key. This is not recommended. An example is to use the domain name, request URL, and user cookie as the key, which means that a page will be cached n times for different users. In most cases In most cases this operation is not required.

  • proxy_cache_min_uses is the minimum number of requests that must use the same key before the response is cached.

  • proxy_cache_methods 为指定要被缓存的请求方式的响应值,默认为 get 和 head,新增其他的需要一起列出来,如上示例所示。

  • proxy_cache_valid 为响应状态码的缓存时间,示例可以为每个状态码缓存指定时间,也可以使用 any 进行全部状态码的缓存。

清除缓存

需要提前加一个配置,用于标识使用 http purge 方法的请求并删除匹配的 url 对应的缓存。

1.在 http {} 上下文中创建新变量,例如 $purge_method, 他依赖于 $request_method 变量:

http {
 ...
 map $request_method $purge_method {
  purge 1;
  default 0;
 }
}
Copy after login

2.在 location {} 块中,已经配置缓存的前提下,引入 proxy_cache_purge 参数来指定清除缓存请求的条件。例如在上一步指定的 $request_method

server {
 listen  80;
 server_name www.example.com;

 location / {
  proxy_pass https://localhost:8002;
  proxy_cache mycache;

  proxy_cache_purge $purge_method;
 }
}
Copy after login

配置完并使之生效之后,就可以发送一条 purge 请求来让缓存失效了,例如:

curl -x purge -d – https://www.example.com/*
Copy after login

在该示例中,将清除具有公共 url 部分(由星号通配符指定)的资源。但这些缓存条目不会从缓存中完全删除:它们会保留在磁盘上,直到它们被视为不活动(由proxy_cache_path 中的 inactive参数决定)的时候才完全删除,或缓存清除器(由 proxy_cache_path 中的 purge 决定),或客户端尝试访问它们的时候。

The above is the detailed content of How to configure Nginx content cache and what are the common parameter configurations. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template