添加配置
看下面的配置:
server { listen 80; server_name 192.168.3.139; root html;
location ~* \.(gif|jpg|jpeg|png|bmp|swf|js|css)$ { set $memcached_key $uri; default_type text/html; memcached_pass 192.168.3.139:11211; error_page 404 = @goto404; }
location @goto404 { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi.conf; rewrite ^(.*)? /goto.php?q=$1 break; }
} |
从配置就可以看出环境来,这是php环境,而且php使用了fastcgi方式,另外php环境中安装了memcache插件,它用作为Memcached的客户端,就是用它来向Memcached写数据,因为Nginx的memcached模块不支持写操作。
该配置的功能在于将图片、swf、js和css文件,当然还可以是其它的文件,这些文件在第一次访问之后就存储在Memcached服务器中,直到耗尽生存期,根据策略的需要,可设置缓存的时间,对于成熟的服务环境可以设定的时间长一点。
编写php文件
下面是goto.php的代码,它是对memcache的应用:
define ( "BASE_DIR", '/www/pic' ); $file = $_GET ['f']; //echo "$file"; if (file_exists ( BASE_DIR . $file )) { $memcache_obj = memcache_connect ( "192.168.3.76", 11211 ); $value = file_get_contents ( BASE_DIR . $file); memcache_add ( $memcache_obj, $file, $value, true, 86400 ); header("Location: {$file}"); } else{ header("Status: 404 Not Found"); } ?>
|
在这段代码中,我们的图片存储在/www/pic目录下,将生存期设置为1天。
需要注意的一点是,对于这里的php环境只是用它来将数据存放入Memcached,对图片的使用就是html的事了。
例如:
[root@pic html]# pwd /usr/local/nginx0.8.53/html [root@pic html]# vi tm.html
|