环境推荐使用openresty,自带了挺多模块的,如果直接使用nginx,需要对缺少的模块进行添加,添加教程参照百度或者OpenResty教程
1、本地站点ETag缓存
示范开启静态文件缓存
环境:
nginx -v
nginx version: openresty/1.15.8.3
(该版本Nginx原生有ETag,默认启用了,如果没有需要对ETag模块进行添加,添加后使用etag on;命令开启)
server {listen 80;server_name localhost;#....其他配置删除了location / {root html;index index.html index.htm;}location ~ .*\.(js|css|gif|jpg|jpeg|png|bmp|swf|flv|html|htm)$ {expires 1d;#缓存一天过期}}
第一次请求时花费37ms
内容未变的情况下后续访问请求响应的状态码会是304(无更改)花费19ms
2、对反向代理开启缓存
2.1nginx.conf中http模块加入如下代码定义一个缓存策略
#-----------------nginx cache configure start
proxy_cache_path /ngx_cache levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=30d use_temp_path=on;
proxy_temp_path /ngx_cache/temp;#临时目录
proxy_cache_key $host$request_uri;#缓存的KEY
#-----------------nginx cache configure end
2.2定义一个反代所需upstream和server
upstream fpa.cn {server 127.0.0.1:81;}server {listen 81;root html;}
2.3将80端口对上面的服务器进行反代设置
server {listen 80;server_name localhost;charset utf-8;#access_log logs/host.access.log main;location / {root html;index index.html index.htm;proxy_pass http://fpa.cn;}error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}}
2.4对反代的请求中的静态文件使用缓存
server {listen 80;server_name localhost;charset utf-8;#access_log logs/host.access.log main;location / {root html;index index.html index.htm;proxy_pass http://fpa.cn;}location ~ .*\.(js|css|gif|jpg|jpeg|png|bmp|swf|flv|html|htm)$ {#proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;#对error等允许使用过期缓存进行返回proxy_cache my_cache;#指定使用my_cache这个缓存配置proxy_cache_key $host$uri$is_args$args;#设置缓存的key(在缓存的文件里开头有KEY:值)proxy_cache_valid 1d;#缓存有效期1天#proxy_ignore_headers Cache-Control;#开启后忽略不允许缓存add_header X-Cache $upstream_cache_status;#将缓存是否命中的结果返回add_header X-Via $server_addr;#将缓存服务器IP返回proxy_pass http://fpa.cn;#反代}error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}}
效果图:
进入配置的缓存目录查看,该页面已被缓存