Nginx uses the proxy_cache directive to set the reverse proxy to cache static resources

Scene

Install Nginx by decompressing the tar package in CentOS7:

How to install Nginx_centos7 tar file in CentOS7 by decompressing the tar package – Programmer Sought

Refer to the above process to realize the establishment of Nginx, and realize the cache setting of static resources.

Note that the above installation directory is in the /opt/nginx directory, and here it is in the /usr/local/nginx directory.

Nginx caches static resources

As a high-performance web server, nginx can cache static resources when proxying requests.

When a user requests a static resource, nginx will first look it up in the local cache. If the resource exists in the cache,

nginx will directly return to the user; if the resource does not exist in the cache, nginx will obtain it from the upstream server,

It is then stored in the local cache and returned to the user.

In the Nginx server, there is also a temporary cache configuration set using the proxy_ cache directive, which uses the md5 method

After hashing the request link, a cache file directory is generated according to the specific configuration to save the response data.

Prepare two virtual machines and install and configure two Nginx servers, one ip is 192.168.148.141 as the Web cache server,

The other is 192.168.148.142 as the content source web server.

Note:

blog:
Domineering Rogue Temperament_C#, Architecture Road, SpringBoot-CSDN Blog

Implementation

1. First configure the web cache server 192.168.148.141

Edit the nginx.conf configuration file and add the following configuration in the http block

 #Proxy temporary directory
    proxy_temp_path /usr/local/nginx/proxy_temp_dir;
    #Web cache directory and parameter settings
    proxy_cache_path /usr/local/nginx/proxy_cache_dir levels=1:2 keys_zone=cache_one:50m inactive=1m max_size=500m;

Pay attention to the two paths here, because nginx is installed under /usr/local/nginx, so the two paths that appear above are configured on the basis of this path, and need to be configured according to

You need to change to the corresponding path.

The command configured above

proxy_temp_path is used to set the temporary directory used by the cache server when receiving the response content from the content source server.

The proxy_cache_path command is used to set the cache directory, and the meaning of related parameters:

The /usr/local/nginx/proxy_cache_dir parameter indicates the user-defined cache file storage directory.

The levels parameter indicates the hierarchical directory structure under the cache directory, which is created based on the hashed request URL address, and the directory name is intercepted from the end of the hashed string.

The keys_zone parameter specifies the name and size of the cache area. For example, cache_one:50m means the name of the cache area is cache_one, and the space in the memory is 50MB.

The inactive parameter indicates that the cache that has not been accessed within the specified time is actively cleared. For example, 1m clears caches that have not been accessed within a minute, 1h means 1 hour, 1d means 1 day, etc.

The max_size parameter indicates the size of the specified disk space, such as 500m, 10g.

It should be noted that when Nginx is caching, it will first be written to the temporary directory specified by proxy_temp_path.

Therefore, it is recommended that the directory set by the proxy_ cache_path proxy_temp_path directive should be in the same file system to avoid disk I/O consumption between different file systems.

Then add the relevant configuration of the temporary cache in the server block

?
    server {
        listen 80;
        server_name 192.168.148.141;

        #charset koi8-r;

        #access_log logs/host.access.log main;
        #Add two response header information, used to obtain the accessed server address and whether the cache is successful
        add_header X-Via $server_addr;
        add_header X-Cache $upstream_cache_status;
        location / {
            #Set cache region name
            proxy_cache cache_one;
            # Combining the domain name, URI, and parameters into the Key value of the Web cache, Nginx hashes it according to the Key value
            proxy_cache_key $host$uri$is_args$args;
            #Set different cache times for different HTTP status codes
            proxy_cache_valid 200 10m; #200 cache for 10 minutes
            proxy_cache_valid 304 1m; #304 Cache for 1 minute
            proxy_cache_valid 301 302 1h; #301 302 cache for 1 hour
            proxy_cache_valid any 1m; #Other unset status codes are cached for 1 minute
     #Set up reverse proxy
            proxy_pass http://192.168.148.142;
    
        }

?

Pay attention to add the location

Detailed configuration:

proxy_cache is used to set the cache area name.

proxy_cache_key is used to set the key value composition rules of the hash. If it is omitted, Nginx will use the default key value composition rules.

proxy_cache_key specific built-in variable description:

$host: The domain name of the server.

$uri: The part between the domain name and the parameter.

$is_args: When there are URL parameters, what is the value? , otherwise an empty string.

$args: save URL parameters, such as a=1 & amp;b=2, empty string if there is no parameter.

The proxy_cache_valid command sets different cache times for different HTTP status codes. The first parameter of the command indicates the status code, and the second parameter indicates the cache time.

The add_header directive adds two response headers, in order to check whether it is cached correctly on the browser side.

X-Via indicates the server address, which is obtained by using the built-in variable $server_addr, and another X-Cache indicates the resource cache status, which is obtained by using the built-in variable $upstream_cache_status.

There are 7 return values of $upstream_cache_status:

HIT means cache hit

MISS indicates a miss and the request is passed to the backend

EXPIRED indicates that the cache has expired and the request is sent to the backend

UPDATING indicates that the cache is being updated and the old answer will be used

When STALE indicates that the cache cannot be updated from the backend server, the old cache content is returned

BYPASS indicates that the cache is bypassed

REVALIDATED means that after the proxy_cache_revalidate command is enabled, when the cache content expires, Nginx will verify whether the cache content has expired through an If-Modified-Since request header.

This status is returned.

Notice:

For the user’s request, the response header set by the add_header instruction will be viewed in the browser’s Response Headers only if the processing is successful.

2. Access test

Place several test files in the content source server 192.168.148.142 for access testing.

The default configuration used by nginx here, so upload the file to the /usr/local/nginx/html directory

For example, create a new badao.html here

<h1>192.168.148.142/badao.html!</h1>

Then start the nginx of the two servers and visit in the browser

http://192.168.148.141/badao.html

At this time, open the browsing development tool-network-click bdao.html, find the response header, check the values of X-Via and X-Cache, you can see that it is MISS at this time

HIT on second request within one minute

for the second request

At this time, check the cache directory /usr/local/nginx/proxy_cache_dir configured on the cache server 192.168.148.141,

Cache files can be seen. Here use the tree command to view

The command needs to pass

yum -y install tree

It can only be used after installation.

For in-depth verification, after the request on 141, the corresponding file on 142 is immediately renamed, and 141 can still be obtained through the cache within one minute.

Revisiting after the cache expires will prompt 404