Leah Sapan
Leah Sapan

Reputation: 3791

Proper way to serve updated files without user refreshing on nginx

This is a pretty core question. I have a django app that I run in an nginx/gunicorn configuration. Nginx is responsible for proxying to gunicorn, but it also serves the static files of the project directly.

The issue is, when I update the static files, the browser doesn't load the latest version. Sometimes a refresh fixes it, but sometimes it requires clearing the cache. (I should mention I'm using require.js, which does not help).

To alleviate this issue I'm doing this trick:

VERSION = '2.03'
STATIC_URL = '/static/' + VERSION + '/'
STATIC_ROOT = BASE_DIR + '/static/' + VERSION + '/'

This way, when I change static files, I simply bump the version. But for various reasons, I need to stop doing this. Is there a way to configure nginx to better serve updated static files when they are available?

I'm just not sure if the browser or nginx is to blame.

Update: Here's my nginx configuration with the comments removed:

upstream mycoolsite_server {
  server unix:/webapps/mycoolsite/run/gunicorn.sock fail_timeout=0;
}

server {
    listen       80;
    server_name  www.mycoolsite.com;
    return       301 http://mycoolsite.com$request_uri;
}

server {

    listen   80;
    server_name mycoolsite.com 42.42.42.42;

    client_max_body_size 4G;

    access_log /webapps/mycoolsite/logs/nginx-access.log;
    error_log /webapps/mycoolsite/logs/nginx-error.log;

    location /static/ {
        alias   /webapps/mycoolsite/site/static/;
    }

    location /media/ {
        alias   /webapps/mycoolsite/site/media/;
    }

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_set_header Host $http_host;

        proxy_redirect off;

        if (!-f $request_filename) {
            proxy_pass http://mycoolsite_server;
            break;
        }
    }

    # Error pages
    error_page 500 502 503 504 /500.html;
    location = /500.html {
        root /webapps/mycoolsite/site/static/;
    }
}

Upvotes: 3

Views: 4344

Answers (1)

rkirmizi
rkirmizi

Reputation: 364

You can set expire for the static files in nginx configuration. For example if you don't want to cache css, js and png files. you can define sth. like:

location ~* \.(css|js|png)$ {
    expires 0;
    break;
}

so they won't been cached. But i assume you are making ./manage.py collectstatic after you change your static files on your repository or dev. environment.

Upvotes: 5

Related Questions