[SOLVED] This is a duplicate. Answer is in this question
(Port wasn't included in resource urls generated by django in production setup, change in nginx .conf fixed it. I was locally testing the production setup on a specific port. Apparently this would not be a problem if the default port is used in production.)
I am (locally) creating a (Dockerized) production setup for my Django project. I am using Django with Gunicorn and NGINX. NGINX handles static and media files, (which works fine as I can access them by manually entering the correct URL). While Django does correctly link to static files, the URLs to media files are wrong.
For media files it skips the port in the URL, while for static files it does not. I tried to remove trailing /
and to set MEDIA_URL = 'localhost:1337/media/'
. I don't understand why the static URLs are correct and the media URLs are not, as I set them up in the exact same way:
settings.py:
DEBUG = False
STATIC_URL = '/static/'
STATIC_ROOT = 'path/to/static'
MEDIA_URL = '/media/'
MEDIA_ROOT = 'path/to/media'
- Example of (correct) Django link to static file:
http://localhost:1337/static/path/to/file
. - Example of Django link to uploaded media file:
http://localhost/media/path/to/file
. - Actual location of media file:
http://localhost:1337/media/path/to/file
.
as requested, nginx.conf:
upstream django_app {
server web:8000;
}
server {
listen 80;
location / {
proxy_pass http://django_app;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
}
location /static/ {
alias /path/to/static/;
}
location /media/ {
alias /path/to/media/;
}
}