search
HomeOperation and MaintenanceNginxA brief analysis of nginx caching and cleaning (code sharing)

之前的文章《浅析安卓app和微信授权登录及分享完整对接(代码分享)》中,给大家了解了安卓app和微信授权登录、分享完整对接。下面本篇文章给大家了解nginx的缓存和清理,有需要的朋友可以参考一下,希望对你们有所助。

A brief analysis of nginx caching and cleaning (code sharing)

背景

由于服务器的各方面配置都太低,经不起消耗,所以基本上所有动态的内容都以缓存形式展现,除了部分的交互使用动态意外。

但是每次修改了动态的内容,缓存有没过期,这样得必须手动清理缓存了。于是尝试使用nginx+ngx_cache_purge模块

ngx_cache_purge模块的安装

检查是否安装

nginx -V   #大写的V

看到如下:

nginx version: nginx/1.18.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC)
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'

安装

因为已经安装过nginx,所以无法./configure

nginx -v  #小写的V

查看版本

nginx version: nginx/1.18.0

在官网的地址http://nginx.org/download/上找对对应的版本,down下来,解压

wget http://nginx.org/download/nginx-1.18.0.tar.gz
tar -zxvf nginx-1.18.0.tar.gz

在这里http://labs.frickle.com/files/找到ngx_cache_purge的最新版本,down下来,解压

wget http://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz
tar -zxvf ngx_cache_purge-2.3.tar.gz

备份启动文件

cp /sbin/nginx /sbin/nginx.bak

重新编译刚才下载的nginx把模块带进去编译

cd nginx-1.18.0 #第一步
# ./configure + nginx -V  看到的 configure arguments + '--add-module=/usr/software/ngx_cache_purge-2.3'
./configure --prefix=/etc/nginx (略) --add-module=/root/app/ngx_cache_purge-2.3  #第二步
make  #第三步

是make编译, 不是make install ,make install会覆盖原来已经安装好的内容。编译必须没有错误,才能继续下一步

检查是否编译成功

./objs/nginx -V

如果编译成功,把objs下的nginx文件 拷贝到/sbin目录下,然后检查是否正常

/sbin/nginx -V

重启

/sbin/nginx -c /etc/nginx/nginx.conf
/sbin/nginx -s reload

检查下进程,正常会看到多出的2个进程

ps -ef|grep nginx
root      9266     1  0 17:08 ?        00:00:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
root      9267  9266  0 17:08 ?        00:00:00 nginx: worker process
root      9268  9266  0 17:08 ?        00:00:00 nginx: cache manager process  #多出的
root      9269  9266  0 17:08 ?        00:00:00 nginx: cache loader process  #多出的
root      9272  1261  0 17:08 pts/0    00:00:00 grep --color=auto nginx

没有的话,kill进程,然后重启

缓存的清理

关于nginx的更多设置请看这篇

别忘了配置

location ~ /clear_cache(/.*) {
    #删除指定缓存区域cache_one的特定缓存文件$1$is_args$args
    proxy_cache_purge cache_one $1$is_args$args;
    #运行本机和10.0.217.0网段的机器访问,拒绝其它所有
    allow           127.0.0.1;
    allow           10.0.217.0/24;
    deny          all;
}

这样清理某个缓存文件的时候地址前面加上/clear_cache即可,如 :清理文件https://www.chuchur.com/js/a.js,输入https://www.chuchur.com/clear_cache/js/a.js,看到Successful purge表明清理成功。

可以每次修改动态内容之后,自动触发缓存清理器操作

一些问题

该缓存的没缓存, 不该缓存的缓存了。

排除问题

add_header      Nginx-Cache     "$upstream_cache_status";

查看Headers里的Nginx-Cache状态 是Hit还是Miss

允许 一些头部信息:

proxy_ignore_headers Expires;
proxy_ignore_headers Cache-Control;

控制哪些缓存, 哪些不缓存:

set $nocache 0;
# 以 aaa,bbb,ccc 开头的不缓存
if ($request_uri ~ ^/(aaa|bbb|ccc)) {
    set $nocache 1;
}

proxy_cache_bypass $nocache;

# cookie 里面设置了nocache,或者 参数传值里有aaa,bbb 的不缓存,满足一个即可

proxy_no_cache $cookie_nocache $arg_aaa $arg_bbb;

为什么明明设置了不缓存Nginx-Cache状态也是BYPASS, 拿到的还是缓存信息?

一般都是get请求 ,post请求不会缓存数据

通过Network=>Size观察 ,居然是 (memory cache) ,也就是 ,浏览器直接从内存取的数据, 未从服务器获取最新数据

解决: 在get请求时传递随机字符串 : 

var time = Date.now();
$.get("/aaa/bbb/ccc?time=" + time);

至此缓存和不缓存,已经缓存的自动更新的问题顺利解决。

推荐学习:Nginx基础入门视频教程

The above is the detailed content of A brief analysis of nginx caching and cleaning (code sharing). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:禅境花园. If there is any infringement, please contact admin@php.cn delete
NGINX: An Introduction to the High-Performance Web ServerNGINX: An Introduction to the High-Performance Web ServerApr 29, 2025 am 12:02 AM

NGINX started in 2002 and was developed by IgorSysoev to solve the C10k problem. 1.NGINX is a high-performance web server, an event-driven asynchronous architecture, suitable for high concurrency. 2. Provide advanced functions such as reverse proxy, load balancing and caching to improve system performance and reliability. 3. Optimization techniques include adjusting the number of worker processes, enabling Gzip compression, using HTTP/2 and security configuration.

NGINX vs. Apache: A Look at Their ArchitecturesNGINX vs. Apache: A Look at Their ArchitecturesApr 28, 2025 am 12:13 AM

The main architecture difference between NGINX and Apache is that NGINX adopts event-driven, asynchronous non-blocking model, while Apache uses process or thread model. 1) NGINX efficiently handles high-concurrent connections through event loops and I/O multiplexing mechanisms, suitable for static content and reverse proxy. 2) Apache adopts a multi-process or multi-threaded model, which is highly stable but has high resource consumption, and is suitable for scenarios where rich module expansion is required.

NGINX vs. Apache: Examining the Pros and ConsNGINX vs. Apache: Examining the Pros and ConsApr 27, 2025 am 12:05 AM

NGINX is suitable for handling high concurrent and static content, while Apache is suitable for complex configurations and dynamic content. 1. NGINX efficiently handles concurrent connections, suitable for high-traffic scenarios, but requires additional configuration when processing dynamic content. 2. Apache provides rich modules and flexible configurations, which are suitable for complex needs, but have poor high concurrency performance.

NGINX and Apache: Understanding the Key DifferencesNGINX and Apache: Understanding the Key DifferencesApr 26, 2025 am 12:01 AM

NGINX and Apache each have their own advantages and disadvantages, and the choice should be based on specific needs. 1.NGINX is suitable for high concurrency scenarios because of its asynchronous non-blocking architecture. 2. Apache is suitable for low-concurrency scenarios that require complex configurations, because of its modular design.

NGINX Unit: Key Features and CapabilitiesNGINX Unit: Key Features and CapabilitiesApr 25, 2025 am 12:17 AM

NGINXUnit is an open source application server that supports multiple programming languages ​​and provides functions such as dynamic configuration, zero downtime updates and built-in load balancing. 1. Dynamic configuration: You can modify the configuration without restarting. 2. Multilingual support: compatible with Python, Go, Java, PHP, etc. 3. Zero downtime update: Supports application updates that do not interrupt services. 4. Built-in load balancing: Requests can be distributed to multiple application instances.

NGINX Unit vs. Other Application ServersNGINX Unit vs. Other Application ServersApr 24, 2025 am 12:14 AM

NGINXUnit is better than ApacheTomcat, Gunicorn and Node.js built-in HTTP servers, suitable for multilingual projects and dynamic configuration requirements. 1) Supports multiple programming languages, 2) Provides dynamic configuration reloading, 3) Built-in load balancing function, suitable for projects that require high scalability and reliability.

NGINX Unit: The Architecture and How It WorksNGINX Unit: The Architecture and How It WorksApr 23, 2025 am 12:18 AM

NGINXUnit improves application performance and manageability with its modular architecture and dynamic reconfiguration capabilities. 1) Modular design includes master processes, routers and application processes, supporting efficient management and expansion. 2) Dynamic reconfiguration allows seamless update of configuration at runtime, suitable for CI/CD environments. 3) Multilingual support is implemented through dynamic loading of language runtime, improving development flexibility. 4) High performance is achieved through event-driven models and asynchronous I/O, and remains efficient even under high concurrency. 5) Security is improved by isolating application processes and reducing the mutual influence between applications.

Using NGINX Unit: Deploying and Managing ApplicationsUsing NGINX Unit: Deploying and Managing ApplicationsApr 22, 2025 am 12:06 AM

NGINXUnit can be used to deploy and manage applications in multiple languages. 1) Install NGINXUnit. 2) Configure it to run different types of applications such as Python and PHP. 3) Use its dynamic configuration function for application management. Through these steps, you can efficiently deploy and manage applications and improve project efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor