Nginx Tutorial (vi): Using the fastcgi cache of Nginx cache

Source: Internet
Author: User
Tags md5 hash naming convention

Enable FASTCGI Caching

<br\>
Edit the virtual host configuration file that must be enabled for caching.

    1. Nano/etc/nginx/sites-enabled/vhost

Add the following line to the top of the file beyond the server{} directive:

    1. Fastcgi_cache_path/etc/nginx/cache levels=1:2 keys_zone=myapp:100m inactive=60m;
    2. 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$ {}:

    1. Fastcgi_cache MYAPP;
    2. 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:

    1. Service Nginx Configtest

Heavy-duty Nginx:

    1. Service Nginx Reload

The complete vhost configuration file is as follows:

  1. Fastcgi_cache_path/etc/nginx/cache levels=1:2 keys_zone=myapp:100m inactive=60m;
  2. Fastcgi_cache_key "$scheme $request_method$host$request_uri";
  3. server {
  4. Listen 80;
  5. root/usr/share/nginx/html;
  6. Index index.php index.html index.htm;
  7. server_name example.com;
  8. Location/{
  9. Try_files $uri $uri//index.html;
  10. }
  11. Location ~ \.php$ {
  12. Try_files $uri = 404;
  13. Fastcgi_pass Unix:/var/run/php5-fpm.sock;
  14. Fastcgi_index index.php;
  15. Include Fastcgi_params;
  16. Fastcgi_cache MYAPP;
  17. Fastcgi_cache_valid 60m;
  18. }
  19. }
Testing whether the fastcgi cache is in effect

<br\>
Create a/usr/share/nginx/html/time.php with the following content:

    1. <?php
    2. echo Time ();
    3. ?>

Use curl or your Web browser to request this file multiple times.

    1. [Email protected]:~# Curl Http://localhost/time.php;echo
    2. 1382986152
    3. [Email protected]:~# Curl Http://localhost/time.php;echo
    4. 1382986152
    5. [Email protected]:~# Curl Http://localhost/time.php;echo
    6. 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:

    1. 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:

    1. #Cache Everything by default
    2. Set $no _cache 0;
    3. #Don ' t cache POST requests
    4. if ($request _method = POST)
    5. {
    6. Set $no _cache 1;
    7. }
    8. #Don ' t cache if the URL contains a query string
    9. if ($query _string! = "")
    10. {
    11. Set $no _cache 1;
    12. }
    13. #Don ' t cache the following URLs
    14. if ($request _uri ~* "/(administrator/|login.php)")
    15. {
    16. Set $no _cache 1;
    17. }
    18. #Don ' t cache if there is a cookie called PHPSESSID
    19. if ($http _cookie = "Phpsessid")
    20. {
    21. Set $no _cache 1;
    22. }

To apply the "$no _cache" variable to the appropriate directive, place the following line in location?. PHP $ {},

    1. Fastcgi_cache_bypass $no _cache;
    2. 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.

    1. 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:

    1. 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:

    1. <?php
    2. $cache _path = '/etc/nginx/cache/';
    3. $url = Parse_url ($_post[' url ');
    4. if (! $url)
    5. {
    6. Echo ' Invalid URL entered ';
    7. Die ();
    8. }
    9. $scheme = $url [' scheme '];
    10. $host = $url [' Host '];
    11. $requesturi = $url [' path '];
    12. $hash = MD5 ($scheme. ' GET '. $host. $requesturi);
    13. Var_dump (unlink ($cache _path. substr ($hash,-1). ‘/‘ . substr ($hash, -3,2). ‘/‘ . $hash));
    14. ?>

Send a POST request with a URL that needs to be purged to this file.

    1. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.