簡體   English   中英

無法在Django中使用Nginx服務器處理靜態文件

[英]cannot server static files with nginx in django

我正在將nginx作為Web服務器運行django。 配置后,似乎我總是得到404的靜態文件。 這是我的配置

base.py

STATIC_ROOT = os.path.join(PROJECT_DIR, "static")
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(PROJECT_DIR, 'static_files'),
]

nginx.conf

    upstream django {
        server unix:///tmp/mysite.sock;
    }


    # configuration of the server
    server {
        listen  5000;
        server_name server localhost:5000;  address or FQDN
        charset     utf-8;
        client_max_body_size 75M;   

      location /static {
        alias /Users/del/projects/app-backend/static/; 
      }

      location ~ ^/(images|javascript|js|css|flash|media|static)/  {
        autoindex on;
        root /Users/del/projects/app-backend/static/; 
      }

      location / {
        uwsgi_pass  django;
        include     /Users/del/perso/django/library/uwsgi;

       } 
    }

我已經確保運行python manage.py collectstatic ,並且文件實際上是在/static/文件夾下生成的

您似乎已經猜到了對nginx應該起作用的方法,但不了解別名和root的工作原理:

root設置位置的父目錄。 父目錄中必須存在具有相同名稱的物理目錄:

root    /var/www
directory     |----- /static
file                    |----- image.jpg

root /var/www location /static現在將提供/var/www/static 網址http://example.com/static/image.jpg將投放/var/www/static/image.jpg

結構相同,但alias /var/www/static location /s現在將提供/var/www/static 網址http://example.com/s/image.jpg將投放/var/www/static/image.jpg

因此,您的簡單配置將是:

server {
    root /var/www; # Set root at server level

    location /static {
        expires max;
    }

    location / {
        uwsgi_pass django;
    }
 }

我不知道您需要使用正則表達式。 如果您在模板中始終使用Django的static標簽,則無需匹配“ / images”等等。

最后,由於regex中包含static且regex模式優先於字符串匹配,因此將在app-backend/static/static查找您對URL中對/static/所有引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM