前端采用NGINX部署静态资源,Nginx缓存策略

404 阅读1分钟

就是作为笔记写一下。

因为这里的前端是客户端渲染,

  1. index.html是亘古不变的文件名,所以对它采用协商缓存,其实也可以采用不缓存的方案,因为它本身体积比较小。见配置17行
  2. 因为js,css这些文件都是加载在index.html中,所以他们本身是可以强缓存的,只有index.html更新了,里面引用的js,css也会更新
server {
    listen       8093;
    server_name  localhost;

    #access_log  /var/log/nginx/host.access.log  main;
    root /svideoWeb/dist;

    location / {
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }
    location ~* \.(js|css|svg)$ {
        expires 1y;  # 强缓存,设置缓存时间为1年
        add_header Cache-Control "public";  # 允许客户端和代理服务器缓存文件
    }

    location = /index.html {
        expires -1;  # 协商缓存,每次请求都会向服务器验证缓存有效性
        add_header Cache-Control "no-store";  # 不允许客户端和代理服务器缓存文件
    }
    location ^~ /api/ {
            rewrite ^/api/(.*)$ /interface/$1 break;
            client_max_body_size 50M;
            proxy_pass http://127.0.0.1:8090;
            proxy_redirect      default;
            proxy_set_header    Host    $host:$server_port;
            proxy_set_header    X-Forwarded-Host $host:$server_port;
            proxy_set_header    X-Forwarded-Server $host:$server_port;
            proxy_set_header    X-Real-IP $remote_addr;
            proxy_set_header    X-Forwarded-For  $proxy_add_x_forwarded_for;			
        }
    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
   
}