Nginx configuration proxy cache and browser cache

Static resource cache

Static file caching can reduce bandwidth loss. The files of the upstream server can be cached to Nginx, and the files of Nginx can also be cached to the browser.

Browser cache:
Accelerate user access and improve the experience of a single user (browser visitor), cached locally.
Nginx cache:

  • Cache on the nginx side to improve the user experience of all access to the nginx side.
  • Improve the speed of accessing upstream servers.
  • User access will still generate request traffic.

Insert picture description here

1 Control the browser cache

The browser mainly controls the cache expiration time, which can be left unset.

location /files {
    alias /home/imooc;
    # expires 10s; #10s后浏览器缓存失效
    # expires @22h30m; #到22:30失效
    # expires -1h; #在这之前1h已经过期
    expires epoch; #相当于no-cache
    # expires off; #关闭Nginx缓存,使用浏览器默认
    # expires max; #最大时间,永不过期
    # add_header Cache-Control no-store;
}

浏览器F12
Cache-Control: max-age=10
Date: Sun, 03 Jan 2021 05:35:04 GMT
Expires: Sun, 03 Jan 2021 05:35:14 GMT

2 Set up Nginx reverse proxy cache

upstream cluster {
    server 192.168.233.130:8080;
    server 192.168.233.130:8088;
}

# proxy_cache_path 设置缓存目录
# keys_zone 设置共享内存以及占用空间大小,mycache是缓存名字
# max_size 设置缓存大小
# inactive 超过此时间则被清理
# use_temp_path 临时目录,使用后会影响nginx性能
# levels 是否创建二级文件夹
proxy_cache_path /usr/local/nginx/upstream_cache keys_zone=mycache:5m max_size=1g inactive=1m use_temp_path=off;

# 配置server
server {
    listen      80;
    server_name     www.awecoder.com;
    
    location / {
        proxy_pass  http://cluster;

        # 启动缓存
        proxy_cache mycache;
        # 针对200和304状态码缓存时间为8小时
        proxy_cache_valid   200 304 8h;
    }
}

Guess you like

Origin blog.csdn.net/LIZHONGPING00/article/details/112976466