如何通过nginx提供django媒体文件?

问题描述 投票:21回答:2

我是Nginx的新手,我已成功将我的django项目绑定到Nginx。但是我不能提供我的静态文件,我想我错误地设置了我的媒体文件夹的位置。这是我的文件树:

root_directory
     my_django_project
         ...
         manage.py
         app1
         app2
         media
           admin
           css
           js
           ...

我的nginx.conf就像:

        server {
                listen 192.168.1.9:80;
                server_name localhost;
                # site_media - folder in uri for static files                                                                                                

            location /media/  {
            root /home/nazmi/workspace/portal/media/;                                                                                       
                }

location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js|mov) {
  access_log   off; # po co mi logi obrazków :)                                                                                                              
  expires      30d;
}
                location / {
                        # host and port to fastcgi server                                                                                                    
                        fastcgi_pass 127.0.0.1:8080;
            fastcgi_param PATH_INFO $fastcgi_script_name;
                        fastcgi_param REQUEST_METHOD $request_method;
                        fastcgi_param QUERY_STRING $query_string;
                        fastcgi_param CONTENT_TYPE $content_type;
                        fastcgi_param CONTENT_LENGTH $content_length;
            fastcgi_pass_header Authorization;
                        fastcgi_intercept_errors off;
                        }
                access_log      /var/log/nginx/localhost.access_log main;
                error_log       /var/log/nginx/localhost.error_log;
        }
}

当我打开管理页面时,所有css页面都会出现404错误。你能告诉我怎样才能正确设置我的媒体路径?

django nginx media
2个回答
46
投票

这是我如何设置nginx服务器的示例

server {
    server_name example.com www.example.com;
    location /static {
        autoindex on;
        alias /home/myusername/myproject/static/;
    }
    location /media {
        autoindex on;
        alias /home/myusername/myproject/media/;
    }
    location / {
        proxy_pass http://127.0.0.1:8000;
    }
}

我在本地端口8000上使用Gunicorn为django提供服务。(这就是proxy_pass的用途)

Nginx wiki example configuration也可以帮到你。请注意,在他们的静态文件服务中,他们指定允许的文件类型并使用“root”而不是“alias”,但它们是相似的。

这个ServerFault问题可能会有所帮助。


0
投票

以下代码适用于我:

server {
server_name example.com www.example.com;
location /static {
    autoindex on;
    **alias /home/myusername/myproject/;**
}
location /media {
    autoindex on;
    **alias /home/myusername/myproject/;**
}
location / {
    proxy_pass http://127.0.0.1:8000;
}

}

我根据之前的答案加粗了不同的部分。

© www.soinside.com 2019 - 2024. All rights reserved.