nginx

关注公众号 jb51net

关闭
首页 > 网站技巧 > 服务器 > nginx > Nginx Proxy_cache缓存配置

Nginx+Proxy_cache高速缓存配置

作者:奔跑、在路上

本文主要介绍了Nginx+Proxy_cache高速缓存配置,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

前言

Nginx已经具备Squid所拥有的Web缓存加速功能、清除指定URL缓存的功能。而在性能上,Nginx对多核CPU的利用,胜过Squid不少。另外,在反向代理、负载均衡、健康检查、后端服务器故障转移、Rewrite重写、易用性上,Nginx也比Squid强大得多。这使得一台Nginx可以同时作为“负载均衡服务器”与“Web缓存服务器”来使用。

一、 安装nginx和ngx-purge:

ulimit -SHn 65535
cd /usr/local/nginx
tar zxvf ngx_cache_purge-1.4.tar.gz
cd nginx-1.6.1/
./configure --user=nginx --group=nginx --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_gzip_static_module --add-module=../ngx_cache_purge-1.4
make && make install
cd ../

二、 Nginx Cache配置:

http  {  \\添加以下内容 ,不能定义在server{}上下文中 }
.......
#定义从后端服务器接收的临时文件的存放路径
proxy_temp_path /data/proxy_temp_dir;
#设置Web缓存区名称cache_one,内存缓存空间100MB,1天没有被访问的内容自动清除,硬盘缓存空间10GB。
proxy_cache_path /nginx/cache/first levels=1:2:1 keys_zone=cache_one:100m inactive=1d max_size=10g;   

upstream backend_server {
server 10.1.1.1:8080 weight=1 max_fails=2 fail_timeout=30s;
server 10.1.1.2:8080 weight=1 max_fails=2 fail_timeout=30s;
} 
server
{
listen 80;
server_name localhost;
index index.html index.htm;
root  html;

location /
{
#如果后端的服务器返回502、504、执行超时等错误,自动将请求转发到upstream负载均衡池中的另一台服务器,实现故障转移。
proxy_next_upstream http_502 http_504 error timeout invalid_header;
proxy_cache cache_one;
#对不同的HTTP状态码设置不同的缓存时间
proxy_cache_valid 200 304  2h;
#以域名、URI、参数组合成Web缓存的Key值,Nginx根据Key值哈希,存储缓存内容到二级缓存目录内
proxy_cache_key $host$uri$is_args$args;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://127.0.0.1;
expires 1d;
}
location ~ /purge(/.*)
{
#设置只允许指定的IP或IP段输入正确的密码才可以清除URL缓存。
auth_basic “Please Insert User And Password”;
auth_basic_user_file /tmp/htpasswd;
allow 127.0.0.1;
allow 10.1.1.0/24;
deny all;
proxy_cache_purge cache_one $host$1$is_args$args;
}
........

三、ginx Cache测试:

#启动Nginx服务,/usr/local/nginx/sbin/nginx 

#然后配置好resin端口设置为8080  

#如果需要刷新缓存的url地址为:  http://10.1.1.10/purge/ 

四、如何清除缓存:

清除缓存有两种方法,第一种是直接通过nginx.conf配置文件定义的/purge虚拟目录去清除,第二种方法可以通过shell脚本去批量清除:

附上Shell脚本清空缓存的内容:

#! /bin/sh
#Auto Clean Nginx Cache Shell Scripts
#2013-06-12  wugk
#Define Path
CACHE_DIR=/data/www/proxy_cache_dir/
FILE="$*"
 #To determine whether the input script,If not, then exit 判断脚本是否有输入,没有输入然后退出
if
  [  "$#" -eq "0" ];then
  echo "Please Insert clean Nginx cache File, Example: $0 index.html index.js"
  sleep 2 && exit
fi
  echo "The file : $FILE to be clean nginx Cache ,please waiting ....."
 #Wrap processing for the input file, for grep lookup,对输入的文件进行换行处理,利于grep查找匹配相关内容
for i in `echo $FILE |sed 's//\n/g'`
do
   grep -ra  $i  ${CACHE_DIR}| awk -F':' '{print $1}'  > /tmp/cache_list.txt
    for j in `cat/tmp/cache_list.txt`
  do
    rm  -rf  $j
    echo "$i  $j  is  Deleted Success !"
  done
done

到此这篇关于Nginx+Proxy_cache高速缓存配置的文章就介绍到这了,更多相关Nginx Proxy_cache缓存配置内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文