【问题标题】:Proper way to serve updated files without user refreshing on nginx无需用户在 nginx 上刷新即可提供更新文件的正确方法
【发布时间】:2015-05-20 10:28:37
【问题描述】:

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

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

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

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

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

我只是不确定是浏览器还是 nginx 的问题。

更新:这是我删除了 cmets 的 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/;
    }
}

【问题讨论】:

  • 我假设您在每次更新后都在运行 ./manage.py collectstatic?你能发布你的nginx配置吗?
  • 是的,这太容易了。 :P 我发布了配置。

标签: django nginx gunicorn static-files


【解决方案1】:

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

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

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

【讨论】:

  • 问题是出于性能原因我仍然希望允许浏览器缓存,但浏览器不会向服务器发送某种类型的标头,让服务器确定是否需要下载新版本?
  • 好的,我明白了。这是你的解药:) docs.djangoproject.com/en/1.7/ref/contrib/staticfiles/…
  • 关闭!这是一个很好的解决方案,但不幸的是它会破坏与 r.js 的兼容性。
  • 最终我最终使用了 nginx expire,但我使用 2h 用于 js 和 css。谢谢!
  • 对于未来的读者来说,禁用缓存的正确方法是“expires off”(这是默认设置),因为“expires 0”告诉 nginx 实际上添加标题“Cache-Control: max-age=吨。”默认为 1 个月到期。 nginx.org/en/docs/http/ngx_http_headers_module.html#expires
猜你喜欢
  • 2021-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-08
  • 2016-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多