Home  >  Article  >  Operation and Maintenance  >  How to use Nginx for cache control of HTTP requests

How to use Nginx for cache control of HTTP requests

王林
王林Original
2023-08-02 14:01:121871browse

How to use Nginx for cache control of HTTP requests

Cache control of HTTP requests is an important means of optimizing website performance. It can reduce the number of times the server processes requests and improve the response speed of the website. As a high-performance web server and reverse proxy server, Nginx provides flexible cache control functions. This article will introduce how to use Nginx for cache control of HTTP requests.

1. Use proxy cache

Nginx provides the proxy cache function, which can cache the response results from the upstream server and reduce the number of requests to the upstream server. To use proxy caching, you can add the following configuration to the Nginx configuration file:

http {
  proxy_cache_path /var/cache/nginx 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$uri$is_args$args;
      proxy_cache_valid 200 302 10m;
      proxy_cache_valid 404 1m;
      proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
      proxy_ignore_headers Cache-Control;
      proxy_ignore_headers Set-Cookie;
      proxy_hide_header Set-Cookie;
      proxy_pass http://upstream_server;
    }
    ...
  }
}

In the above configuration, proxy_cache_path is used to set the cache path and related parameters. levels=1:2 means creating a level 1 directory and a level 2 directory in the cache path to improve efficiency. keys_zone is used to set the name and memory size of the cache area, which can be adjusted according to actual needs. max_size indicates the maximum capacity of the cache area, and inactive indicates the cache expiration time, that is, caches that have not been accessed within 60 minutes will be deleted. use_temp_path=off means disabling the temporary path, which can improve performance.

In the specific server configuration, specify the URL that needs to be cached through the location directive. The proxy_cache instruction indicates enabling caching, and the proxy_cache_key instruction specifies the cache key value. Multiple variables can be used to splice the cache key value. proxy_cache_validSpecifies the cache validity period of different HTTP status codes. For example, the response results of 200 and 302 status codes are valid within 10 minutes, and the response results of 404 status code are valid within 1 minute. proxy_cache_use_stale Used to specify whether to use an expired cache when an error, timeout, or update occurs on the upstream server. The proxy_ignore_headers and proxy_hide_header directives can be used to ignore or hide certain attributes in response headers.

After the configuration is completed, restart the Nginx service to make the configuration take effect. At this time, Nginx will cache the matching URL. When the same URL is requested again, the response result will be obtained directly from the cache without requesting the upstream server again.

2. Use browser cache

In addition to proxy cache, you can also use browser cache to reduce network requests. Nginx can control the browser cache behavior by setting Cache-Control and Expires in the response header.

An example is as follows:

http {
  ...
  server {
    ...
    location /static/ {
      expires max;
      add_header Cache-Control public;
    }
    ...
  }
}

In the above configuration, the expires directive is set to max, which means that the expiration time of the response result is set to the maximum value. That is, it never expires. The add_header directive adds the Cache-Control header to the response result and sets it to public, indicating that public caching is allowed.

In specific URL matching rules, different caching strategies can be set according to different needs. For example, static resources usually do not change frequently, so expires can be set to a longer time to allow the browser to cache the resources; while dynamically generated pages can be set to not cache or have a shorter cache time.

3. Use conditional caching

Conditional caching is a mechanism for communication between the client and the server. It can decide whether to use caching based on the conditions of the request. Nginx sets the Last-Modified and ETag in the response header, and the If-Modified-Since and If-None-Match in the request header. To implement conditional caching.

The example is as follows:

http {
  ...
  server {
    ...
    location / {
      if_modified_since before;
      add_header ETag "123456";
      if_none_match $http_if_none_match;
      if_modified_since off;
      ...
    }
    ...
  }
}

In the above configuration, the if_modified_since directive is used to determine whether the If-Modified-Since in the request header is earlier than the server The set Last-Modified; the add_header instruction adds the ETag header to identify the uniqueness of the resource; the if_none_match instruction is used to determine Whether the If-None-Match in the request header matches the ETag set by the server; the if_modified_since and if_none_match instructions respectively correspond# The values ​​of the ##If-Modified-Since and If-None-Match request headers.

By configuring conditional caching, when the client sends a request, it can be judged whether to use the cache based on the

Last-Modified and ETag returned by the server. If the resource has not changed, the server can return 304 Not Modified, and the client obtains the resource from the cache; if the resource has changed, the server returns the new resource.

4. Caching Strategy

In order to better control the caching behavior, you can set different caching strategies according to different URLs. Generally, the URL of static resources is stable and a longer cache expiration period can be set; while the URL of dynamic pages may change frequently, and a shorter cache expiration period can be set.

The example is as follows:

http {
  ...
  server {
    ...
    location /static/ {
      expires 7d;
      add_header Cache-Control public;
    }

    location /dynamic/ {
      expires 1h;
      add_header Cache-Control no-cache;
    }
    ...
  }
}

In the above configuration, URLs starting with

/static/ match static resources, set the expiration time to 7 days, and allow public caching; URLs starting with /dynamic/ match dynamic resources, set the expiration time to 1 hour, and disable caching.

Through reasonable caching strategies, you can improve website performance while ensuring that users obtain the latest resources.

Summarize

Using Nginx for cache control of HTTP requests is an effective means to optimize website performance. Through proxy caching, browser caching and conditional caching, the number of requests to the server can be reduced and the response speed of the website can be improved. In the specific caching strategy, different cache expiration periods need to be set according to different URLs to provide a better user experience.

Reference: https://nginx.org/

The above is the detailed content of How to use Nginx for cache control of HTTP requests. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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