NGINX 提供静态文件 - django 项目没有样式

NGINX serve static files - django project has no styling

我成功部署了我的 Django 应用程序,但我无法使用 Nginx 传递静态文件。我已按照所有部署到生产环境的说明进行操作。当我检查页面时,我看到的只是空的静态文件夹 谁能找出错误?

非常感谢

nginx.conf

 10 upstream app_upstream {
  9     server app:8080;
  8 }
  7
  6 server {
  5     listen 80;
  4     listen 443;
  1     server_name #######;
  2
  3     location /static/ {
  4         alias /static/;
  5     }
  6
  7     location /media/ {
  8         alias /media/;
  9     }
 10
 11     location / {
 12         proxy_set_header Host $host;
 13         proxy_pass http://app_upstream;
 14     }
 15 }

settings.py

14
 13 STATIC_URL = '/static/'
 12 STATIC_ROOT = '/static/'

docker-compose.yml

....
 12   app:
 13     build: .
 14     ports:
 15       - 8000:8000
 16       - 8080:8080
 17     env_file:
 18       - db_${RTE}.env
 19     volumes:
 20       - .:/app/
 21       - static:/static/
 22       - media:/media/
 23     depends_on:
 24       - db
 25
 26   nginx:
 27     build: nginx/
 28     ports:
 29       - 443:443
 30       - 80:80
 31     volumes:
 32       - ./nginx/${RTE}/conf.d/:/etc/nginx/conf.d/
 34       - static:/static/
 35       - media:/media/
 36     depends_on:
 37       - app
 38
 39 volumes:
 40   static:
...

我 docker-compose 时的错误消息:

nginx_1  | 2022/01/10 16:26:17 [error] 10#10: *8 open() "/static/custom.css" failed (2: No such--More
--More--

遇到过类似的问题(但未使用 Docker),也许这可能会有所帮助。

如果您的根项目中有一个用于项目级静态文件的静态文件夹,并且如果您在 docker-compose 或 Docker文件,不太了解Docker,我想你在生产中仍然需要,那么重命名settings.py中的STATIC_URL和STATIC_ROOT可能会有所帮助因为该命令会尝试将所有应用程序中的所有静态文件收集到一个文件夹中。尝试这样的事情:

    STATIC_URL = '/staticfiles/'
    STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles'))
    STATICFILES_DIRS = [str(BASE_DIR.joinpath('static'))]

请注意,您还必须更新 Nginx 文件,即

    server {
            ...
            location /staticfiles/ {
            ...
           }