无需用户在 nginx 上刷新即可提供更新文件的正确方法

Luk*_*pan 3 django nginx static-files gunicorn

这是一个非常核心的问题。我有一个在 nginx/gunicorn 配置中运行的 django 应用程序。Nginx 负责代理到gunicorn,但也直接服务于项目的静态文件。

问题是,当我更新静态文件时,浏览器不会加载最新版本。有时刷新会修复它,但有时它需要清除缓存。(我应该提到我正在使用 require.js,这没有帮助)。

为了缓解这个问题,我正在做这个技巧:

VERSION = '2.03'
STATIC_URL = '/static/' + VERSION + '/'
STATIC_ROOT = BASE_DIR + '/static/' + VERSION + '/'
Run Code Online (Sandbox Code Playgroud)

这样,当我更改静态文件时,我只需修改版本。但出于各种原因,我需要停止这样做。有没有办法配置 nginx 以便在可用时更好地提供更新的静态文件?

我只是不确定浏览器或 nginx 是否应该受到指责。

更新:这是我的 nginx 配置,删除了注释:

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/;
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以在 nginx 配置中为静态文件设置过期时间。例如,如果您不想缓存 css、js 和 png 文件。你可以定义…… 喜欢:

location ~* \.(css|js|png)$ {
    expires 0;
    break;
}
Run Code Online (Sandbox Code Playgroud)

所以它们不会被缓存。但是我假设您在更改存储库或开发人员上的静态文件后正在制作 ./manage.py collectstatic 。环境。

  • 对于未来的读者,禁用缓存的正确方法是“expires off”(这是默认值),因为“expires 0”实际上告诉 nginx 添加标头“Cache-Control: max-age=t”。默认为 1 个月到期。http://nginx.org/en/docs/http/ngx_http_headers_module.html#expires (4认同)