简体   繁体   中英

Caching static files isn't working when using nginx as a reverse proxy

I have an ExpressJS app running behind nginx which I setup as reverse proxy. I've also setup some caching for static files like images, js and css. The problem is, they don't seem to actually be caching. The requests to those files always returns a 200 status code instead of a 304. If I inspect the headers in dev tools, the Expires header is never the same as it was the last time I requested the file. It always gets reset to a new value. Is there something I've missed in my configuration?

I'm using nginx 1.4.4.

Thanks.

upstream stats {
  ip_hash;
  server localhost:3000;
}

server {
  server_name app.example.com;

  access_log /var/log/nginx/stats.access.log;
  error_log /var/log/nginx/stats.error.log debug;

  root /srv/www/stats/public;

  location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarder-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://stats;
    proxy_redirect off;
  }

  location ~* .(ico|css|js|gif|jpg|png)$ {
    expires 7d;
    log_not_found off;
  }
}

It is normal that the expiry time that you see in a header changes with each request because, as the doc says :

A time in the “Expires” field is computed as a sum of the current time and time specified in the directive.

(Emphasis added.) The current time is the time of the request. Since the current time changes with each request, then the expiry time changes too. If what you want is to use the time of last modification of the file instead you'd use expires modified 7d .

Now, by setting an expiry date to 7 days into the future, you are telling the browser to not even bother to check again before the expiry. You will get an 304 when the browser checks again, in 7 days. If you want the browser to always check when it tries to load the resource again, then set expires 0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM