nginx 自制lua删除静态缓存

nginx缓存有两种
一种是临时缓存,可以proxy_cache_purge可以清除
配置示例如下:


##
#临时缓存http配置区
##
#proxy_temp_path /var/www/static;
proxy_cache_path /var/www/proxy_cache_dir levels=1:2 keys_zone=cache_one:200m inactive=1d max_size=800m;
server {
	listen 80 default_server;
	server_name ~^\w[-\w.+]*\w+$;
	##
	#临时缓存server配置区2
	##
	add_header X-Via $server_addr;
	add_header X-Cache $upstream_cache_status;
	location ~ /purge {
		proxy_cache_purge cache_one $1$is_args$args;
	}
	##
	# JS和CSS缓存时间设置.
	##
	location ~* .*\.(js|css)?$
	{
		if ( !-e $request_filename) {
			proxy_pass http://$passipa;
		}
		##
		# 临时缓存server配置区3
		##
		expires 1;
		proxy_cache cache_one;
		proxy_cache_key $uri$is_args$args;
		proxy_cache_valid 200 12h;
		proxy_cache_valid 304 12h;
		proxy_cache_valid 301 302 1d;
		proxy_cache_valid any 1m;
	}
}

一种是永久缓存,文件放在硬盘上,这种只能想别的办法删除静态文件,但是需要lua扩展


server {
	##
	#用于清除缓存(需要安装ngx_cache_purge模块);
	#临时缓存清除/purge(/.*)
	##
	location ~ /purge {
		#proxy_cache_purge cache_one $1$is_args$args;
		#使用 http://host/purge?/path/to/youfile.js
		default_type text/plain;
		set $cache_home /var/www/static;
		content_by_lua '
		function file_exists(path)
			local file = io.open(path, "rb")
			if file then file:close() end
			return file ~= nil
		end
		--注释 ngx.var.args 为链接参数
		if ngx.var.args ~= nil then
		local realpath=ngx.var.cache_home..ngx.var.args
			if file_exists(realpath) then
				os.remove(realpath)
				ngx.say(realpath)
			end
		end
		';
	}

	##
	# 图片缓存时间设置.
	##
	root /var/www/static; #缓存静态文件.
	location ~* .*\.(js|css)$
	{
		if ( !-e $request_filename) {
			proxy_pass http://$passipa;
		}
		proxy_store on; # 开启本地永久缓存.
		proxy_store_access user:rw group:rw all:r; # 设置缓存的读写规则.
		proxy_temp_path /var/www/static; # 设置反向代理接受的数据临时存储文件的目录,配置生效时候会自动创建.
	}
}
点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注