Nginx使用教程(六):使用Nginx缓存之FastCGI缓存

启用FastCGI缓存



编辑必须启用缓存的虚拟主机配置文件。

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

将以下行添加到server{}指令之外的文件顶部:

  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";

“fastcgi_cache_path”指令指定缓存(/etc/nginx/cache)的位置,其大小(100m),内存区域名称(MYAPP),子目录级别和非活动定时器。
位置可以在硬盘上的任何地方; 但是,大小必须小于您的服务器的RAM +交换,否则你会收到一个错误,“无法分配内存”。 如果缓存在“inactive”选项指定的特定时间内没有被访问(这里为60分钟),Nginx将删除它。
“fastcgi_cache_key”指令指定如何哈希缓存文件名。 Nginx基于此指令使用MD5加密访问的文件。
在location ~ .php$ { }里添加如下行:

  1. fastcgi_cache MYAPP;
  2. fastcgi_cache_valid 200 60m;

“fastcgi_cache”指令引用我们在“fastcgicache_path”指令中指定的内存区域名称,并将缓存存储在此区域中。
默认情况下,Nginx根据这些响应头里指定的时间决定存储缓存对象的时间:X-Accel-Expires / Expires / Cache-Control。
如果缺少这些头,“fastcgi_cache_valid”指令用于指定默认缓存生命周期。 在上面输入的语句中,只缓存状态代码为200的响应。 也可以指定其他响应代码。
测试配置:

  1. service nginx configtest

重载Nginx:

  1. service nginx reload

完整的vhost配置文件如下:

  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.  
  4. server {
  5.     listen   80;
  6.  
  7.     root /usr/share/nginx/html;
  8.     index index.php index.html index.htm;
  9.  
  10.     server_name example.com;
  11.  
  12.     location / {
  13.         try_files $uri $uri/ /index.html;
  14.     }
  15.  
  16.     location ~ \.php$ {
  17.         try_files $uri =404;
  18.         fastcgi_pass unix:/var/run/php5-fpm.sock;
  19.         fastcgi_index index.php;
  20.         include fastcgi_params;
  21.         fastcgi_cache MYAPP;
  22.         fastcgi_cache_valid 200 60m;
  23.     }
  24. }

测试FastCGI缓存是否生效



创建/usr/share/nginx/html/time.php,内容如下:

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

使用curl或您的Web浏览器多次请求此文件。

  1. root@droplet:~# curl http://localhost/time.php;echo
  2. 1382986152
  3. root@droplet:~# curl http://localhost/time.php;echo
  4. 1382986152
  5. root@droplet:~# curl http://localhost/time.php;echo
  6. 1382986152

如果缓存工作正常,您应该在缓存响应时在所有请求上看到相同的时间戳。
执行缓存位置的递归列表以查找此请求的缓存。
root@droplet:~# ls -lR /etc/nginx/cache/
/etc/nginx/cache/:
total 0
drwx—— 3 www-data www-data 60 Oct 28 18:53 e

/etc/nginx/cache/e:
total 0
drwx—— 2 www-data www-data 60 Oct 28 18:53 18

/etc/nginx/cache/e/18:
total 4
-rw——- 1 www-data www-data 117 Oct 28 18:53 b777c8adab3ec92cd43756226caf618e
我们还可以使Nginx为响应添加一个“X-Cache”头,指示缓存是否被丢失或命中。
在server{}指令上面添加以下内容:

  1. add_header X-Cache $upstream_cache_status;

重新加载Nginx服务,并使用curl执行详细请求以查看新标题。
root@droplet:~# curl -v http://localhost/time.php
* About to connect() to localhost port 80 (#0)
* Trying 127.0.0.1…
* connected
* Connected to localhost (127.0.0.1) port 80 (#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
不需要缓存的页面



某些动态内容(例如认证所需页面)不应缓存。 可以基于诸如“requesturi”,“requestmethod”和“http_cookie”的服务器变量来排除这样的内容被高速缓存。
如下例子:

  1. #Cache everything by default
  2. set $no_cache 0;
  3.  
  4. #Don't cache POST requests
  5. if ($request_method = POST)
  6. {
  7.     set $no_cache 1;
  8. }
  9.  
  10. #Don't cache if the URL contains a query string
  11. if ($query_string != "")
  12. {
  13.     set $no_cache 1;
  14. }
  15.  
  16. #Don't cache the following URLs
  17. if ($request_uri ~* "/(administrator/|login.php)")
  18. {
  19.     set $no_cache 1;
  20. }
  21.  
  22. #Don't cache if there is a cookie called PHPSESSID
  23. if ($http_cookie = "PHPSESSID")
  24. {
  25.     set $no_cache 1;
  26. }

要将“$no_cache”变量应用到相应的指令,请将以下行放在location〜.php $ {}中,

  1. fastcgi_cache_bypass $no_cache;
  2. fastcgi_no_cache $no_cache;

“fasctcgicachebypass”指令忽略之前由我们设置的条件相关的请求的现有缓存。 如果满足指定的条件,“fastcginocache”指令不缓存请求。

清除缓存



缓存的命名约定基于我们为“fastcgicachekey”指令设置的变量。

  1. fastcgi_cache_key "$scheme$request_method$host$request_uri";

根据这些变量,当我们请求“http//localhost/time.php”时,以下是实际值:

  1. fastcgi_cache_key "httpGETlocalhost/time.php";

将此字符串传递到MD5哈希将输出以下字符串:
b777c8adab3ec92cd43756226caf618e
这就是高速缓存的文件名,就像我们输入的“levels = 1:2”子目录。 因此,目录的第一级将从这个MD5字符串的最后一个字符命名为1个字符,即e; 第二级将具有在第一级之后的最后2个字符,即18.因此,该高速缓存的整个目录结构如下:
/etc/nginx/cache/e/18/b777c8adab3ec92cd43756226caf618e
基于这种缓存命名格式,您可以用您最喜欢的语言开发一个清除脚本。 对于本教程,我将提供一个简单的PHP脚本,它清除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. ?>

向此文件发送带需要清除的URL的POST请求。

  1. curl -d 'url=http://www.example.com/time.php' http://localhost/purge.php

该脚本将根据是否清除缓存而输出true或false。 请确保从高速缓存中排除此脚本,并限制访问。

标签:缓存Nginx 发布于:2019-11-21 07:08:58