[英]Django on Nginx serving static files but not media files when debug is False
我的 django 应用程序在调试设置为 True 的情况下在生产中正常运行,当我关闭它时,该应用程序不再提供媒体文件(由用户上传),但静态文件可以正常提供。
这是我的设置:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '../static/')
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads', 'media')
MEDIA_URL = '/uploads/media/'
DOCUMENTS_ROOT = os.path.join(BASE_DIR, 'uploads', 'media', 'documents')
这是我的基本网址:
urlpatterns = [
path('i18n/', include('django.conf.urls.i18n')),
path('auth/', include("django.contrib.auth.urls")),
path('traveller/', include('travellers.urls')),
path('service/', include('drivers.urls')),
path('admin/', include("management.urls")),
path('events/', include('events.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
这是我的 Nginx 站点配置:
upstream app_server{
server unix:/home/envs/bus_env/run/bus.sock fail_timeout=10;
}
server {
listen 80;
# add here the ip address of your server
# or a domain pointing to that ip (like example.com or www.example.com)
server_name ***.***.***.***;
keepalive_timeout 20;
client_max_body_size 4G;
access_log /home/envs/bus_env/logs/nginx-access.log;
error_log /home/envs/bus_env/logs/nginx-error.log;
location /static/ {
alias /home/envs/bus_env/static/;
}
location /media/ {
# media files, uploaded by users
autoindex on;
alias /home/envs/bus_env/backend/uploads/media/;
}
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;
}
}
这是请求个人资料图片时的 nginx 访问日志,例如:
"GET /uploads/media/staff/profile_pictures/viber_image_V2JdnkG.jpg HTTP/1.1" 404 799
这是我的上传文件夹层次结构:
.
└── media
├── documents
│ ├── drivers
│ └── staff
│ ├── 10
│ ├── 11
│ ├── 12
│ ├── 14
│ ├── 15
│ ├── 16
│ ├── 17
│ ├── 18
│ ├── 19
│ ├── 20
│ ├── 21
│ ├── 4
│ ├── 5
│ ├── 8
│ ├── 9
│ ├── amine
│ ├── hello
│ ├── sdfsdg
│ └── wassim
├── drivers
│ └── profile_pictures
├── staff
│ └── profile_pictures
└── travellers
└── profile_pictures
我尝试了很多东西,看到了很多线程,比如手动设置媒体根变量,将别名更改为根,删除自动索引......似乎没有任何效果。
在 nginx 上如下更改您的媒体配置
location /uploads/media/ {
# media files, uploaded by users
autoindex on;
alias /home/envs/bus_env/backend/uploads/media/;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.