我刚刚在digitalocean上部署了django应用程序,但是由于nginx不能提供用户上传的媒体文件,因此我遇到了问题。
这是我的nginx配置:
upstream app_server {
server unix:/home/sayc/run/gunicorn.sock fail_timeout=0;
}
server {
listen 80;
server_name www.shelteratyourcrossroads.com;
keepalive_timeout 5;
client_max_body_size 4G;
access_log /home/sayc/logs/nginx-access.log;
error_log /home/sayc/logs/nginx-error.log;
location /static/ {
alias /home/sayc/staticfiles/;
}
# checks for static file, if not found proxy to app
location / {
try_files $uri @proxy_to_app;
}
location @proxy_to_app {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://app_server;
}
}
以下是settings.py中的一些设置:
...
# Static
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'staticfiles')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
# Media
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
# CKEditor Configuration
CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js'
CKEDITOR_UPLOAD_PATH = 'uploads/'
CKEDITOR_IMAGE_BACKEND = 'pillow'
CKEDITOR_CONFIGS = {
'default' : {
'toolbar' : None,
}
}
...
models.py:
class Post(models.Model):
...
image = models.ImageField(upload_to='posts/%Y/%m/%d', blank=True)
...
class Profile(models.Model):
...
image = models.ImageField(upload_to='users/%Y/%m/%d', null=True, blank=True)
...
上面models.py文件中每个类的图像字段表示媒体目录中有两个子文件夹-media/posts
和media/users
。此外,还有另一个子文件夹media/uploads
-由CKEDITOR_UPLOAD_PATH设置添加的。这就是三个。
我希望这足以帮助调试我的nginx配置出了什么问题。
答案 0 :(得分:0)
您需要添加
location /media/ {
alias /home/sayc/<project_name>/media/; # change project_name
}
在您的Nginx配置中。
自
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'staticfiles')
我无法猜测您的媒体文件的完整路径:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')