zoukankan      html  css  js  c++  java
  • Nginx缓存配置之手动清除缓存

    访问我的博客

    前言

    前文介绍了利用 nginx 的 nginx_ngx_cache_purge 模块来实现缓存功能,并设置了缓存时间为一天。

    但是如果前端修改了页面,比如首页,由于 Nginx 缓存的存在,网站首页并不会立即生效,而是要等到缓存过期。这样明显不是我们想要的结果,所以需要进行手动使 Nginx 缓存失效。以下为操作详解。

    基础环境

    Nginx 配置文件拆分

    在企业 Nginx 应用中,Nginx 配置文件应该根据域名不同来进行拆分,然后再 nginx.conf中进行include引入。这样的好处是便于管理配置文件,便于修改配置文件, 而 nginx.conf 文件中只保留 upstream 以及其他通用配置信息。

    在 Nginx 的 conf 目录下创建文件夹 include, 用于保存拆分的配置文件。

    mkdir include
    

    拆分的规则可以如下:

    • 桌面版(WEB)的 Nginx 配置文件,可以命名为 nginx_web.conf
    • 手机版(WAP)的 Nginx 配置文件,可以命名为 nginx_wap.conf
    • 安卓的 Nginx 配置文件,可以命名为 nginx_apk.conf
    • 苹果的 Nginx 配置文件,可以命名为 nginx_ios.conf
    • 清除缓存的配置文件,可以命名为 purge.conf

    /usr/local/nginx/conf/nginx.conf 中引入拆分的配置文件, 在配置文件中的 http 节点下进行引入

    http{
    
      #......
      
      # 注意 purge.conf 必须要第一个引用!!!
      include include/purge.conf;
      # 引入其他配置文件
      include include/nginx_web.conf;
      #include include/nginx_wap.conf;
      #include include/nginx_apk.conf;
      #include include/nginx_ios.conf;
    }
    

    配置缓存清除

    cd /usr/local/nginx/conf/include
    vi purge.conf
    
    #purge.conf 文件内容为:
    server {
        listen       80;
        server_name 192.168.200.129;# 此处我配置的是本机ip
        charset utf8;
    
        location ~ /purge(/.*) {
            allow   all;# 访问此接口的白名单,all代表所有人都可以访问该路径
            # tmpcache 为前文中 proxy_cache_path 里配置的 keys_zone 的值
            # www.domain.com$1$is_args$args 表示缓存key的名称,清除某一域名下的缓存,可以指定参数 
            # $1 代表正则匹配中的第一组
            proxy_cache_purge cachefile www.domain.com$1$is_args$args;
        }
    }
    
    # 保存 purge.conf 文件
    

    测试清除缓存

    如果要进行缓存清除,首先需要有缓存文件,此处参照前文 Nginx缓存配置 中,访问 www.domain.com/testpage2 ,刷新页面,直到缓存已经生成,即 X-Cache 的状态为 HIT

    进入 cd /tmp/cache/ ,查看已经生成了缓存文件

    mark

    # 测试 nginx 配置是否正确
    /usr/local/nginx/sbin/nginx -t
    # 如果提示 is ok,说明配置没有问题,否则需要修改
    
    # 重启 Nginx 
    /usr/local/nginx/sbin/nginx -s reload
    

    浏览器访问(也可以通过 curl 命令来访问):

    # 清除key为 www.domain.com/ 的缓存
    192.168.200.129/purge/    
    # 清除 key 为 www.domain.com/testpage2 页面缓存
    192.168.200.129/purge/testpage2
    

    如果返回

    mark

    则表示清除成功。

    资源下载

    示例nginx配置文件

  • 相关阅读:
    error occurred during initialization of vm
    Service Discovery protocol(SDP)
    nRF51822EK_PRO
    Binder
    android samsung note3  device not found
    BLE pairing vs. bonding
    remote link Centos6.6 Horrible Slow
    depmod -a
    start and end call use itelephony and how to pick up a call
    WebService
  • 原文地址:https://www.cnblogs.com/vcmq/p/9484381.html
Copyright © 2011-2022 走看看