无法使用 uwsgi 服务器将 django 静态文件提供给 nginx 反向代理

Unable to serve django static files using uwsgi server to the nginx reverse proxy

我使用 uwsgi 作为服务器,nginx 作为 运行 django 项目的反向代理。

项目结构如下(这里我只列出了需要的folder/files):

war
├── katana
│   ├── wapps
│   │   ├── app1
│   │   └── app2
│   └── wui
│       ├── settings.py
│       └── wsgi.py
└── static
    ├── css
    │   └── test.css
    ├── img
    │   └── test.img
    └── js
        └── test.js

settings.py中的静态配置如下:

STATIC_URL = '/static/'
STATICFILES_DIRS = [
        os.path.join(BASE_DIR, 'static')
    ]
DATA_UPLOAD_MAX_MEMORY_SIZE = 10242880
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')

wsgi.py如下:

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "katana.wui.settings")

application = get_wsgi_application()

uwsgi 是服务器启动使用: uwsgi -b 65535 --socket :4000 --workers 100 --cpu-affinity 1 --module katana.wui.wsgi --py-autoreload 1

nginx conf如下:

events {
  worker_connections  1024;  ## Default: 1024
}

http {
    include     conf/mime.types;

    # the upstream component nginx needs to connect to
    upstream uwsgi {
        server backend:4000; # for a web port socket (we'll use this first)
    }

    # configuration of the server
    server {
        # the port your site will be served on
        listen      8443 ssl http2 default_server;

        # the domain name it will serve for
        server_name _; # substitute your machine's IP address or FQDN
        charset     utf-8;

        ssl_certificate     /secrets/server.crt;
        ssl_certificate_key /secrets/server.key;
        ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers         HIGH:!aNULL:!MD5;
        add_header Strict-Transport-Security "max-age=31536000" always;

        # Redirect HTTP to HTTPS
        error_page 497 https://$http_host$request_uri;

        # max upload size
        client_max_body_size 75M;   # adjust to taste
        uwsgi_read_timeout 600s;

        # Finally, send all non-media requests to the Django server.
        location / {
            uwsgi_pass  uwsgi;
            include     /config/uwsgi_params; # the uwsgi_params file you installed
        }
    }
}

项目部署成功但是静态内容(css,js,img)没有加载。 浏览器控制台错误:

GET https://<ip>/static/css/test.css net::ERR_ABORTED 404

注意:我希望 uwsgi 服务器为静态文件提供服务,而 nginx 仅充当反向代理。如果 nginx 配置为提供静态文件,那么它可以做到这一点,但我希望使用 uwsgi 服务器来实现此功能。

Django 在生产环境中不提供静态文件,您应该为它们添加额外的 nginx 位置

location /static {
        alias   /path/to/your/static/;
    }

我建议不要执行以下操作,因为你已经从 nginx 代理了,uwsgi 处理它们毫无意义(你会以这种方式获得更多负载,因为它们需要被代理回来)

如果你还想走这条路 uwsgi staticfile docs