Enable FASTCGI Caching
<br\>
Edit the virtual host configuration file that must be enabled for caching.
- Nano/etc/nginx/sites-enabled/vhost
Add the following line to the top of the file beyond the server{} directive:
- Fastcgi_cache_path/etc/nginx/cache levels=1:2 keys_zone=myapp:100m inactive=60m;
- Fastcgi_cache_key "$scheme $request_method$host$request_uri";
The "fastcgi_cache_path" instruction specifies the location of the cache (/etc/nginx/cache), its size (100m), the memory area name (MYAPP), the subdirectory level, and the inactive timer.
The location can be anywhere on the hard drive; However, the size must be less than the RAM + swap for your server, or you will receive an error, "Unable to allocate memory." If the cache is not accessed at a specific time specified by the "inactive" option (here is 60 minutes), Nginx will delete it.
The "fastcgi_cache_key" instruction specifies how to hash cache file names. Nginx uses MD5 encryption to access files based on this directive.
Add the following line to location ~. php$ {}:
- Fastcgi_cache MYAPP;
- Fastcgi_cache_valid 60m;
The "fastcgi_cache" Directive references the name of the memory region that we specified in the "fastcgicache_path" directive and stores the cache in this zone.
By default, Nginx determines when to store cached objects based on the time specified in these responses: X-accel-expires/expires/cache-control.
If these headers are missing, the "fastcgi_cache_valid" directive is used to specify the default cache life cycle. In the statement entered above, only the response with a status code of 200 is cached. You can also specify additional response codes.
Test configuration:
- Service Nginx Configtest
Heavy-duty Nginx:
- Service Nginx Reload
The complete vhost configuration file is as follows:
- Fastcgi_cache_path/etc/nginx/cache levels=1:2 keys_zone=myapp:100m inactive=60m;
- Fastcgi_cache_key "$scheme $request_method$host$request_uri";
- server {
- Listen 80;
- root/usr/share/nginx/html;
- Index index.php index.html index.htm;
- server_name example.com;
- Location/{
- Try_files $uri $uri//index.html;
- }
- Location ~ \.php$ {
- Try_files $uri = 404;
- Fastcgi_pass Unix:/var/run/php5-fpm.sock;
- Fastcgi_index index.php;
- Include Fastcgi_params;
- Fastcgi_cache MYAPP;
- Fastcgi_cache_valid 60m;
- }
- }
Testing whether the fastcgi cache is in effect
<br\>
Create a/usr/share/nginx/html/time.php with the following content:
- <?php
- echo Time ();
- ?>
Use curl or your Web browser to request this file multiple times.
- [Email protected]:~# Curl Http://localhost/time.php;echo
- 1382986152
- [Email protected]:~# Curl Http://localhost/time.php;echo
- 1382986152
- [Email protected]:~# Curl Http://localhost/time.php;echo
- 1382986152
If the cache is working correctly, you should see the same timestamp on all requests when caching the response.
Executes a recursive list of cache locations to find the cache for this request.
[Email protected]:~# ls-lr/etc/nginx/cache/
/etc/nginx/cache/:
Total 0
Drwx--3 www-data www-data Oct 18:53 E
/ETC/NGINX/CACHE/E:
Total 0
Drwx--2 www-data Www-data Oct 28 18:53 18
/ETC/NGINX/CACHE/E/18:
Total 4
-RW ——-1 www-data www-data 117 Oct-18:53 b777c8adab3ec92cd43756226caf618e
We can also make Nginx add a "X-cache" header to the response, indicating whether the cache is missing or hit.
Add the following on the server{} directive:
- Add_header X-cache $upstream _cache_status;
Reload the Nginx service and use curl to perform a detailed request to see the new title.
[Email protected]:~# curl-v http://localhost/time.php
* About to connect () to localhost port (#0)
* Trying 127.0.0.1 ...
* Connected
* Connected to localhost (127.0.0.1) port (#0)
> get/time.php http/1.1
> user-agent:curl/7.26.0
> Host:localhost
> Accept: */*
>
* HTTP 1.1 or later with persistent connection, pipelining supported
< http/1.1 < Server:nginx < Date:tue, Oct 11:24:04 GMT < content-type:text/html < TRANSFE r-encoding:chunked < Connection:keep-alive < X-cache:hit < * Connection #0 to host localhost-left intact 13830 45828* Closing Connection #0
Pages that do not need to be cached
<br\>
Some dynamic content, such as the pages required for authentication, should not be cached. You can exclude such content from being cached based on server variables such as "RequestUri", "Requestmethod", and "Http_cookie".
The following example:
- #Cache Everything by default
- Set $no _cache 0;
- #Don ' t cache POST requests
- if ($request _method = POST)
- {
- Set $no _cache 1;
- }
- #Don ' t cache if the URL contains a query string
- if ($query _string! = "")
- {
- Set $no _cache 1;
- }
- #Don ' t cache the following URLs
- if ($request _uri ~* "/(administrator/|login.php)")
- {
- Set $no _cache 1;
- }
- #Don ' t cache if there is a cookie called PHPSESSID
- if ($http _cookie = "Phpsessid")
- {
- Set $no _cache 1;
- }
To apply the "$no _cache" variable to the appropriate directive, place the following line in location?. PHP $ {},
- Fastcgi_cache_bypass $no _cache;
- Fastcgi_no_cache $no _cache;
The "fasctcgicachebypass" instruction ignores the existing cache of requests that were previously set by us. If the specified condition is met, the "fastcginocache" directive does not cache the request.
Clear Cache
<br\>
The naming convention for the cache is based on the variables we set for the "fastcgicachekey" directive.
- Fastcgi_cache_key "$scheme $request_method$host$request_uri";
According to these variables, when we request "http//localhost/time.php", the following is the actual value:
- Fastcgi_cache_key "httpgetlocalhost/time.php";
Passing this string to the MD5 hash will output the following string:
b777c8adab3ec92cd43756226caf618e
This is the cache file name, just like the "levels = 1:2" subdirectory we entered. Therefore, the first level of the TOC will be named 1 characters from the last character of the MD5 string, E; The second level will have the last 2 characters after the first level, or 18. Therefore, the entire directory structure of the cache is as follows:
/etc/nginx/cache/e/18/b777c8adab3ec92cd43756226caf618e
Based on this cache naming format, you can develop a purge script in your favorite language. For this tutorial, I'll provide a simple PHP script that clears the cache for the posted URL.
/usr/share/nginx/html/purge.php:
- <?php
- $cache _path = '/etc/nginx/cache/';
- $url = Parse_url ($_post[' url ');
- if (! $url)
- {
- Echo ' Invalid URL entered ';
- Die ();
- }
- $scheme = $url [' scheme '];
- $host = $url [' Host '];
- $requesturi = $url [' path '];
- $hash = MD5 ($scheme. ' GET '. $host. $requesturi);
- Var_dump (unlink ($cache _path. substr ($hash,-1). ‘/‘ . substr ($hash, -3,2). ‘/‘ . $hash));
- ?>
Send a POST request with a URL that needs to be purged to this file.
- Curl-d ' url=http://www.example.com/time.php ' http://localhost/purge.php
The script will output true or false based on whether the cache is cleared. Be sure to exclude this script from the cache and restrict access.
Nginx Tutorial (vi): Using the fastcgi cache of Nginx cache