Django | nginx提供的静态文件未被客户端使用

时间:2019-01-18 05:06:04

标签: python django nginx gunicorn

我有一个django应用,其中包含静态文件的以下设置:

STATIC_DIR = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [STATIC_DIR,]
STATIC_ROOT = '/opt/static/'

我正在使用follwoing gunicorn命令运行django: gunicorn evee.wsgi -b 0.0.0.0:8000

我已配置nginx使用以下conf来提供静态文件和ssl:

  server {
    keepalive_timeout 5;
    listen 443 ssl;
    server_name api.home.com;
    client_max_body_size 4G;
    error_page 500 502 503 504 /500.html;

    # path for static files
    root /opt;

    location / {
      # checks for static file, if not found proxy to app
      try_files $uri @proxy_to_app;
    }

    location @proxy_to_app {
      proxy_set_header Host $host;
      proxy_set_header X-Forwarded-Ssl off;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Port 80;
      proxy_set_header X-Forwarded-Proto $scheme;
      # we don't want nginx trying to do something clever with
      # redirects, we set the Host: header above already.
      proxy_redirect off;
      proxy_pass http://evee:8000;
    }
  }

有趣的是,我能够在客户端中看到CSS。例如,对https://secapi.ril.com/static/admin/css/base.css的请求成功,并返回200响应。我可以在提到的URL上查看所有静态文件,但是django似乎没有使用它们。尝试更改客户端以及私有模式。

我做错什么了吗?这是我上次检查的时间。

2 个答案:

答案 0 :(得分:0)

尝试将nginx配置文件中的静态文件路径添加为:

location /static/ {
    alias   /opt/static/;
}

这里提到了静态文件夹的完整路径。我想您的情况是/opt/static/

答案 1 :(得分:0)

这是我解决此问题的方法。必须编辑nginx.conf文件以配置上游,而不是将其直接重定向到http,并删除了一些正在设置的标头。不知道它有什么不同或为什么起作用。整个设置都在Docker Swarm中运行。

#### SECAPI #####
  upstream app_server {
    # for a TCP configuration
    server evee:8000 fail_timeout=0;
  }

  server {
    keepalive_timeout 5;
    listen 443 ssl;
    server_name api.home.com;
    client_max_body_size 4G;
    error_page 500 502 503 504 /500.html;

    # path for static files
    root /opt;

    location / {
      # checks for static file, if not found proxy to app
      try_files $uri @proxy_to_app;
    }
    location @proxy_to_app {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header Host $http_host;
      # we don't want nginx trying to do something clever with
      # redirects, we set the Host: header above already.
      proxy_redirect off;
      proxy_pass http://app_server;
    }

  }