Nginx服务器缓存设置实例讲解

07-21

用nginx作为web的缓存,位于内容源web服务器与客户端之间。

web缓存的解决方案:

1 Squid Cache

2 Nginx的proxy_cache

先来看下,Nginx的proxy_cache

组成:proxy_cache相关指令集,fastcgi相关指令集

proxy_cache 哪个缓存区将被使用

proxy_cache_path 缓存文件的存放路径

proxy_cache_methods 缓存哪些HTTP方法

proxy_cache_min_users 缓存的最小使用次数

proxy_cache_valid 对不同返回状态码的URL设置不同的缓存时间

proxy_cache_key 设置缓存的key值,Nginx根据key值哈希缓存

安装第三方的ngx_cache_purge模块:

删除指定url缓存

Nginx的web缓存服务

步骤一:

ulimit -SHn 65535

安装 pcre ./configure && make && make install

安装ngx_cache_purge 只要解压就可以了

安装

代码示例:

nginx ./configure --user=www --group=www --add-module=../ngx_cache_purge

--prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_model

&& make && make install

步骤二:

创建2个缓存目录

代码示例:

mkdir -p /data0/proxy_temp_path

mkdir -p /data0/proxy_cache_path

步骤三:

配置nginx.conf的缓存

代码示例:

http{

...

proxy_temp_path ...;

proxy_cache_path ...;

server{

...

proxy_cache cache_name;

proxy_cache_valid ...;

proxy_cache_key ...;

}

}

有关nginx缓存的配置,这里推荐几篇文章,大家也可以参考下:

nginx缓存配置实例

Nginx 设置静态文件缓存时间

nginx缓存本地静态文件

nginx 五种缓存方式

nginx 缓存静态文件的方法

nginx proxy_cache缓存配置

Nginx 前端代理、缓存

接下来说谫,fastcgi缓存配置。

参数说明:

fastcgi_cache 缓存使用哪个缓存区

fastcgi_cache_path 设置缓存文件的存放路径

fastcgi_cache_methodes 设置缓存哪些HTTP方法,默认HTTP GET/HEAD方法

fastcgi_cache_min_users 设置缓存的最小使用次数,默认1

fastcgi_cache_valid 对返回不同状态码的URL设置不同的缓存时间

fastcgi_cache_key 设置web缓存的key值,nginx根据key值md5哈希存储缓存

步骤一:

创建缓存目录:缓存路径必须要在同一磁盘分区

代码示例:

mkdir -p /data0/fastcgi_temp_path

mkdir -p /data0/fastcgi_cache_path

步骤二:

代码示例:

Nginx配置文件

http{

...

fastcgi_temp_path ...;

fastcgi_cache_path ...;

server{

...

fastcgi_cache cache_name;

fastcgi_cache_valid ...;

fastcgi_cache_key ...;

}

}