---
title: "使用Shell脚本批量清除Nginx缓存"
author: "ssxxjjii"
date: "2013-09-19T12:58:04Z"
tags: []
categories: ["互联网"]
slug: "shell-nginx"
draft: false
lastmod: "2013-09-19T12:58:04Z"
id: 1944161
url: "https://tdcq.iteye.com/blog/1944161"
---

[http://wgkgood.blog.51cto.com/1192594/1220828](http://wgkgood.blog.51cto.com/1192594/1220828)

前言\*随着整个互联网的发展，产生了无数大大小小的网站，随之而来用户对网站UI和速度体验也在日益加强，对企业或者个人来说，赢得用户体验也就意味着赢得先机。

那今天我们在这里针对网站速度这方面来一起交流，提高网站速度对于运维工程师、程序员来说变得至关重要。运维工程师首先得在日常网站运维中发现影响网站速度的各种因素得逐个推动然后解决。

提高网站速度体验除了本身网站程序优化外，对于LinuxSA来说还有大量的工作要做，优化系统内核、调整WEB服务器的参数、优化数据库、增加网站架构缓存等等一系列的工作。

对于网站缓存，目前主流的HTTP加速器主要有Varnish、Nginx\_proxy、Squid等，随着Nginx WEB 高速反向代理被各大中型网站使用，其集成缓存的功能（Nginx\_proxy）也日益强大，目前企业中也在大量使用。今天我们来研究一下Nginx\_Proxy缓存如何有效的来清理。如下使用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}'  &gt; /tmp/cache\_list.txt

    for j in \`cat/tmp/cache\_list.txt\`

  do

    rm  -rf  $j

    echo "$i  $j  is  Deleted Success !"

  done

done

#The Scripts exec success and exit 0

如下为执行清除脚本后的截图：

[![](http://img1.51cto.com/attachment/201306/202231727.png "nginx cache")](http://img1.51cto.com/attachment/201306/202231727.png)