When you’re in production, Django does not serve static or media files directly. Instead, you should configure your web server (e.g., Nginx, Apache) to handle and serve media files from the MEDIA_ROOT directory.
Here’s what to do in production:
1. Use a Web Server to Serve Media Files Your production web server should be configured to serve files from the MEDIAROOT directory at the MEDIAURL. This offloads the task of serving files from Django and makes it more efficient for high-traffic environments. Example: Using Nginx to Serve Media Files If you’re using Nginx, you’ll need to configure it to serve media files. In your Nginx configuration file (e.g., /etc/nginx/sites-available/yoursite), you can add a location block for media files: ``` server { listen 80; servername yourdomain.com;
location /media/ {
alias /path/to/your/project/media/;
}
location /static/ {
alias /path/to/your/project/static/;
}
# Your Django site location, like for passing requests to Gunicorn
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
In the example above:
• The alias directive maps the /media/ URL to the actual path on the filesystem (/path/to/your/project/media/).
• You do something similar for static files (/static/).
For static files (CSS, JS, images), you should run python manage.py collectstatic in production, and they will be gathered in the STATIC_ROOT directory. Your web server will then serve them similarly to media files.
In your settings.py:
STATIC_URL = '/static/'
STATICROOT = os.path.join(BASEDIR, 'static')`
And in Nginx:
location /static/ {
`` alias /path/to/your/project/static/;
}
3. Use a CDN for Media/Static Files (Optional)
For better performance and scalability, you can use a CDN (Content Delivery Network) like AWS S3, CloudFront, or another service to serve your media files. In this case, you would upload your media to the CDN, and the MEDIA_URL would point to the CDN instead of your server.
In settings.py, you might have: `MEDIA_URL = 'https://your-cdn-url.com/media/'
You would then handle uploads and file management using a storage backend such as django-storages for S3, or another service.
Summary for Production:
Nginx/Apache: Configure your web server to serve media files from the MEDIA_ROOT directory.
STATICROOT and MEDIAROOT: Make sure these are properly configured in settings.py.
CDN (optional): For large-scale deployments, consider serving media files via a CDN.