First, Introduction
The Nginx version starts with 0.7.48 and supports a squid-like caching feature. This cache is the URL and the associated combination as key, using the MD5 algorithm to hash key, to get the corresponding hash directory path on the hard disk, so that the cache content stored in the directory.
The Nginx Web caching service can only set the expiration time for the specified URL or status code, does not support the purge instructions like squid to manually clear the cache, but we can clear the cache of the specified URL through the Nginx module Ngx_cache_purge.
- Proxy_cache: Cache the contents of the backend server, which may be anything, including static and dynamic, reducing the number of nginx-to-backend communications, saving transmission time and back-end broadband
- Fastcgi_cache: Cache fastcgi generated content, in many cases, PHP generated dynamic content, less than the number of nginx and PHP communication, but also reduce the pressure of PHP and database (MySQL), which is much easier than using a cache like memcached
Pictures from the web
Second, the configuration
Nginx.conf
Fastcgi_cache_path/var/run/nginx-cache levels=1:2 keys_zone=wordpress:100m Inactive=60m;fastcgi_cache_key "$scheme $request _method$host$request_uri "; Fastcgi_cache_use_stale Error timeout Invalid_header http_500;fastcgi_ignore_ Headers Cache-control Expires set-cookie;fastcgi_temp_path /tmp/nginx/fcgi/temp;
Vhost Configuration
server {server_name example.com Www.example.com;access_log/var/log/nginx/example.com.access.log;error_log/var/log /nginx/example.com.error.log;root/var/www/example.com/htdocs;index index.php;set $skip _cache 0;# POST requests and URLs with a query string should always go to phpif ($request _method = POST) {set $skip _cache 1;} if ($query _string = "") {set $skip _cache 1;} # Don ' t cache URIs containing the following segmentsif ($request _uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/| Index.php|sitemap (_index)?. XML ") {set $skip _cache 1;} # Don ' t use the cache for logged in users or recent commentersif ($http _cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-p Ostpass|wordpress_no_cache|wordpress_logged_in ") {set $skip _cache 1;} Location/{try_files $uri $uri//index.php? $args;} Location ~ \.php ($|/) {try_files $uri =404; include Fastcgi_params;fastcgi_split_path_info ^ (. +\.php) (/.+) $;FASTCG I_param path_info $fastcgi _path_info;fastcgi_param script_filename $doCument_root$fastcgi_script_name;fastcgi_pass Unix:/dev/shm/php-socket;fastcgi_cache_bypass $skip _cache;fastcgi_ No_cache $skip _cache;fastcgi_cache wordpress;include fcgi_cache_params;} Location ~/purge (/.*) {fastcgi_cache_purge WORDPRESS "$scheme $request_method$host$1";} Location ~* ^.+\. (ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar| MID|MIDI|WAV|BMP|RTF) $ {access_log off;log_not_found off; expires Max;} Location =/robots.txt {access_log off; log_not_found off;} Location ~/\. {Deny all; Access_log off; log_not_found off;}}
Fcgi_cache_params Configuration
#include fcgi_cache_params, #fastcgi_cache_valid 302 1s;### fcgi-cachefastcgi_cache fcgi;fastcgi_cache_valid 200 302 1s;fastcgi_cache_valid 404 502 503 504 0s;fastcgi_cache_valid any 1m;fastcgi_cache_min_uses 1;fastcgi_cache_use_ Stale error timeout Invalid_header http_500 http_503 updating;fastcgi_ignore_headers cache-control Expires set-cookie;# Add_header x-cache "$upstream _cache_status-$upstream _response_time" Fastcgi_cache_key "$scheme $request_method$ Host$request_uri "
Probably explain the meaning of each parameter:
Fastcgi_cache This instruction is used to set which buffer will be used, zone_name the value of the cache name created by the fastcgi_cache_path instruction
Fastcgi_cache_path Scope: HTTP
Fastcgi_cache_path path [levels=levels] [Use_temp_path=on|off] keys_zone=name:size [Inactive=time] [max_size=size] [ Loader_files=number] [loader_sleep=time] [loader_threshold=time] [Purger=on|off] [purger_files=number] [Purger_ Sleep=time] [purger_threshold=time];
This instruction is used to set the storage path for the cache file, as shown in the following example: Fastcgi_cache_path/data/nginx/cache levels=1:2 keys_zone=cache_one:100m inactive=1d max_size =10g;
A, levels: Specifies that the cache space has a two-level hash directory, set the cache directory layer, Levels=1:2, to create a two-tier directory cache, create up to three tiers. The first-level directory name takes the last character of Fastcgi_cache_key MD5, and the second-level directory name takes the penultimate 2-3 characters, such as: Fastcgi_cache_key MD5 is b7f54b2df7773722d382f4809d65029c, then:
Levels=1:2 to/data/nginx/cache/c/29/b7f54b2df7773722d382f4809d65029clevels=1:2:3 for/data/nginx/cache/c/29/650/ b7f54b2df7773722d382f4809d65029c
B, Keys_zone for this buffer named zone_name,500m refers to the cache space of 500MB;
C, INACTIVE=1D representative if the cache file is not accessed within a day, then delete;
D, max_size=30g represents the maximum hard disk cache is 30G;
setting up caching of multiple disks
FASTCGI_CACHE_PATH/PATH/TO/HDD1 levels=1:2 keys_zone=my_cache_hdd1:10m max_size=10g inactive=60m Use_temp_path =OFF;FASTCGI_CACHE_PATH/PATH/TO/HDD2 levels=1:2 keys_zone=my_cache_hdd2:10m max_size=10g inactive=60m use_temp _path=off;split_clients $request _uri $my _cache { 50% "MY_CACHE_HDD1"; 50% "My_cache_hdd2";} server { ... Location/{ fastcgi_cache $my _cache; }}
put the cache file in memory
Edit/etc/fstab or put/dev/shm
Tmpfs/etc/nginx/cache tmpfs defaults,size=100m 0 0mount-adf-ah | grep TMPFS
It is important to note that the Fastcgi_cache cache is written first in Fastcgi_temp_path and then moved to Fastcgi_cache_path, so the two directories are preferably in the same partition, from the 0.8.9 can be in different partitions, but it is recommended to put the same partition
Fastcgi_cache_methods The directive is used to set which HTTP methods are cached, and the HTTP Get/head method is cached by default.
fastcgi_cache_min_uses How many requests the URL will be cached
fastcgi_cache_valid Reply_code [Reply_code ...] time
This instruction is used to set different cache times for URLs of different return status codes, for example:
Fastcgi_cache_valid 302 10m;fastcgi_cache_valid 404 1m;
Set 202 302 Status URL cache for 10 minutes, 404 status for URL cache for 1 minutes.
Note: If you do not specify a status code and specify the cache time directly, only 200,301,302 of the status code will be cached.
Fastcgi_cache_valid 5m;
any
You can specify that any response code be cached
Fastcgi_cache_valid 302 10m;fastcgi_cache_valid 301 1h;fastcgi_cache_valid any 1m;
The cached parameters can also be set directly in the response header. These have precedence over the cache time setting using the directive
- The "X-accel-expires" header field sets caching time of a response in seconds. The zero value disables caching for a response. If The value starts
@
with the prefix, it sets a absolute time in seconds since Epoch, up to which the response may B E cached.
- If the header does not include the "x-accel-expires" field, parameters of caching is set in the header fields "Expires "or" Cache-control ".
- If the header includes the "Set-cookie" field, such a response won't be cached.
- If the header includes the "Vary" field with the special value "
*
", such a response would not be cached (1.7.7). If the header includes the "Vary" field with another value, such a response would be cached taking to account the Corresp Onding Request header fields (1.7.7).
Fastcgi_cache_key
This instruction is used to set the Web cache key value, Nginx MD5 cache according to the key value. Generally according to $host (domain name), $request _uri (Request path) and other variables to combine into Fastcgi_cache_key.
For example: Fastcgi_cache_key "$scheme $request_method$host$request_uri";
Define Fastcgi_cache key, in the example, the requested URI as the cached Key,nginx will take the key MD5 as a cache file, if the cache hash directory, Nginx will be from the back to the corresponding number of bits as a directory.
Note Be sure to add $request_method as the cache key, otherwise if the first request of the head type causes the subsequent GET request to return empty
fastcgi_temp_path Path [Level1 [Level2 [LEVEL3]]; The default is fastcgi_temp;
This directive is used to set the Fastcgi_cache temp file directory
Fastcgi_temp_path/spool/nginx/fastcgi_temp 1 2;
A temporary file might look like this:
/spool/nginx/fastcgi_temp/7/45/00000123457
fastcgi_cache_use_stale : Fastcgi_cache_use_stale Error | Timeout | Invalid_header | Updating | http_500 | http_503 | http_403 | http_404 | Off ...;
Define which cases are cached with expiration
X-cache head, for commissioning
$upstream _response_time as the expiration time
The $upstream _cache_status variable indicates that this request responds to the state of the cache, in several states, respectively:
- MISS , haven response was wasn't found in the cache and so were fetched from the origin server. The response might then has been cached.
- BYPASS , haven response was fetched from the origin server instead of served from the cache because the request mat Ched a proxy_cache_bypass directive (see Can I Punch a Hole Through My cache? below.) The response might then has been cached.
- EXPIRED , haven entry in the cache has EXPIRED. The response contains fresh content from the origin server.
- STALE , haven content is STALE because the origin server isn't responding correctly, and Proxy_cache_use_stale was Configured.
- UPDATING , haven content is stale because the entry are currently being updated in response to a previous request, a nd proxy_cache_use_stale updating is configured.
- revalidated , Haven proxy_cache_revalidate directive was-enabled and NGINX verified the current cached content was still valid (If-modified-since or if-none-match).
- hits, haven response contains valid, fresh content direct from the cache.
There are some situations that will affect the cache's hit, which requires special attention.
- Nginx Fastcgi_cache in the cache backend fastcgi response, when the response contains "Set-cookie", not cached;
- When the response header contains expires, if the expiration time is greater than the current server time, Nginx_cache caches the response, otherwise it is not cached;
- When the response header contains Cache-control, if the Cache-control parameter value is either No-cache, No-store, or private, it is not cached, and if the Cache-control parameter value is Max-age, it is cached. And the expiration time of the cache set by Nginx is the value of the system current time + mag-age.
Header ("Expires:". Gmdate ("D, D M Y h:i:s", Time () +10000). ' GMT '); Header ("Expires:". Gmdate ("D, D M Y h:i:s", Time ()-99999). ' GMT '); Header ("X-accel-expires:5"); 5sheader ("Cache-control:no-cache"); No Cacheheader ("Cache-control:no-store"); No Cacheheader ("cache-control:private"); No Cacheheader ("cache-control:max-age=10"); Cache 10ssetcookie (' Hello ', "testaaaa"); No cache
Note that there is a pit when using the session, you can use the following to set
Session_cache_limiter ("none"); Session_Start (); Echo Date ("Y-m-d h:i:s", Time ());
Can look at the PHP source code header information expires, etc.
EXT/SESSION/SESSION.C line:1190//... Cache_limiter_func (Private)/* {{{*/{add_header ("Expires:thu, Nov 1981 08:52:00 GMT"); Cache_limiter (Private_no_expire) (Tsrmls_c);} /*}}} *///here 3 or several # #默认是nocacheCACHE_LIMITER_FUNC (nocache)/* {{*/{add_header ("Expires:thu, 1981 08:52: GMT "); /* for http/1.1 conforming clients and the rest (MSIE 5) */Add_header ("Cache-control:no-store, No-cache, Must-revalid Ate, post-check=0, pre-check=0 "); /* for http/1.0 conforming clients */Add_header ("Pragma:no-cache");} /*}}} *///here 2static php_session_cache_limiter_t php_session_cache_limiters[] = {cache_limiter_entry (public) CACHE_ Limiter_entry (private) Cache_limiter_entry (Private_no_expire) cache_limiter_entry (NoCache) {0}}; static int Php_session_cache_limiter (TSRMLS_D)/* {{{*/{php_session_cache_limiter_t *lim; if (PS (Cache_limiter) [0] = = ' + ') return 0; if (SG (headers_sent)) {const char *output_start_filename = PHP_output_get_start_filename (Tsrmls_c); int Output_start_lineno = Php_output_get_start_lineno (Tsrmls_c); if (output_start_filename) {php_error_docref (NULL tsrmls_cc, e_warning, "Cannot send session cache Limiter-h Eaders already sent (output started at%s:%d) ", Output_start_filename, Output_start_lineno); } else {php_error_docref (NULL tsrmls_cc, e_warning, "Cannot send session cache Limiter-headers already sent" ); } return-2; } for (lim = php_session_cache_limiters; lim->name; lim++) {if (!strcasecmp (Lim->name, PS (Cache_limiter) ) {Lim->func (Tsrmls_c); Here 1 return 0; }} return-1;}
Third, clear the cache
Nginx only in the commercial version of the support Proxy_cache_purge instructions to clear the cache, open source Ngx_cache_purge module only support a single key cache cleanup. In order to implement the purge by directory cache can only be developed by itself.
Nginx as the cache server when the resource content is cached as a file, the cache meta-information stored in the shared memory, organized into a red black tree. Each node in the red-black tree represents a cache meta-information. Nginx will use the hash value of the cache key as the key of the red-black tree node. The content cache file is stored on disk with the hash value as the file name.
The simplified description of the Nginx process flow is this: when the request arrives, it is searched in the red-black tree based on the hash value of the cache key. If found, and review the relevant information, if the cache is available, return the appropriate cache file. Otherwise, the back source is fetched.
Because the meta-information is stored as key with the hash value of the cache key, there is no hierarchy in the red-black tree to keep the cache key. such as "/uri/foo" and "/uri/bar" in the meta-information red-black tree is completely not related. To implement clear caching by directory, you need to store the hierarchy relationship in cache key.
You can do this by building a directory tree in shared memory to store hierarchical relationships. The cache key is analogous to a path in the file system, and each level path is stored as a node in the tree. When you need to clear all the caches in a directory, clear all the caches in the node subtree.
Installing the Purge module
The purge module is used to clear the cache
wget HTTP://LABS.FRICKLE.COM/FILES/NGX_CACHE_PURGE-1.2.TAR.GZTAR-ZXVF ngx_cache_purge-1.2.tar.gz
Compile
./configure--prefix=/usr/local/nginx--conf-path=/etc/nginx/nginx.conf--sbin-path=/usr/sbin/nginx--user=www-- Group=webgrp--vhost-domain=example.com--pro-language=php--with-http_ssl_module--with-http_realip_module-- With-http_addition_module--with-http_image_filter_module--with-http_sub_module--with-http_dav_module-- With-http_flv_module--with-http_mp4_module--with-http_gzip_static_module--with-http_concat_module--with-http_ Random_index_module--with-http_secure_link_module--with-http_degradation_module--with-http_sysguard_module-- With-backtrace_module--with-http_stub_status_module--with-http_upstream_check_module--with-google_perftools_ Module--with-http_realip_module--with-http_geoip_module--add-module=/usr/local/ngx_cache_purge-1.2
Iv. Some issues needing attention
After setting the restart Nginx can be effective, this time again to visit the PHP page, it will be cached, you can view/var/logs/nginx/fastcgi_cache_dir This directory is a cache file. Finally, if you change the path of the cache directory, be sure to get rid of the name of the cache, the name of the back-end call also get rid of, if only the cache directory, do not change the cache name, the cache will be cached to the previous path, but the call is called when the new path, There's going to be a situation that can't be found.
Reference articles
http://www.nginxtips.com/configure-nginx-fastcgi-cache/
Http://www.haidx.com/fastcgi-cache-details.html
http://www.just4coding.com/blog/2014/11/01/nginx-purge-directory/
Http://weizhifeng.net/nginx-proxy-cache.html
https://www.nginx.com/blog/nginx-caching-guide/#gs. 6PdbraI
Http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_cache
https://www.cnxct.com/several-reminder-in-nginx-fastcgi_cache-and-php-session_cache_limiter/
https://rtcamp.com/wordpress-nginx/tutorials/single-site/fastcgi-cache-with-purging/
Http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_cache
"Nginx" About Fastcgi_cache