Django生产环境仅Debug开启时才可提供动态生成文件服务问题
Hey there, let's troubleshoot why your media files are throwing 404 errors when DEBUG=False in your Django production setup!
The Core Issue
First off, this is expected behavior from Django: when DEBUG=False, Django's built-in server stops handling media file requests entirely. This is intentional—Django isn't optimized for serving static/media files in production, so we need to hand that responsibility over to a dedicated web server like Nginx or Apache.
Step 1: Double-Check Your Django Settings
First, make sure your media configuration in settings.py is correct:
# settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Local path where media files are stored MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # URL prefix for accessing media files MEDIA_URL = '/media/'
Also, confirm you have the media route in your main urls.py (this only works for local development with DEBUG=True, but it's good to keep for consistency):
# urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # Your other app routes here... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Step 2: Configure Your Web Server to Serve Media Files
Now we need to tell your web server to handle requests to /media/ directly. Here's how to do it for the most common servers:
For Nginx Users
Open your Nginx site configuration file (usually in /etc/nginx/sites-available/ or /etc/nginx/conf.d/), and add this block inside the server section:
server { # Your existing config (listen port, domain, static file rules, etc.) # Handle media file requests location /media/ { alias /full/path/to/your/project/media/; # Replace with your actual MEDIA_ROOT path expires 30d; # Optional: sets cache expiration for media files } }
Save the file and restart Nginx to apply changes:
sudo systemctl restart nginx
For Apache Users
Open your Apache site config (usually in /etc/apache2/sites-available/), and add these lines:
Alias /media/ /full/path/to/your/project/media/ <Directory /full/path/to/your/project/media/> Require all granted Options Indexes FollowSymLinks </Directory>
Restart Apache to make the changes take effect:
sudo systemctl restart apache2
Step 3: Quick Permission Check
Make sure your web server user (usually www-data for both Nginx and Apache) has read access to your media directory:
sudo chown -R www-data:www-data /full/path/to/your/project/media/ sudo chmod -R 755 /full/path/to/your/project/media/
Also, double-check that the generated image file actually exists in MEDIA_ROOT/imgs/img.png—sometimes the 404 is just because the file wasn't created properly!
That should fix the issue and get your media files loading in production with DEBUG=False.
内容的提问来源于stack exchange,提问作者Ritambhara Chauhan

