在DigitalOcean+Apache的Django生产环境中如何托管媒体文件(无S3预算)
Absolutely! You don’t need Amazon S3 to serve media files for your Django app on DigitalOcean with Apache—you can configure Apache to handle media file hosting directly, no paid services required. Let’s break down the steps to get this working properly:
Step 1: Update Your Django Settings
First, make sure your settings.py has the correct configuration for media files. Add or modify these lines:
import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent # Media files configuration MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URLis the URL path users will access media files through (e.g.,https://yourdomain.com/media/profile.jpg).MEDIA_ROOTis the absolute path on your server where uploaded media files will be stored.
Step 2: Configure Apache to Serve Media Files
Apache needs explicit instructions to serve files from your MEDIA_ROOT directory. Open your Apache site configuration file (usually located at /etc/apache2/sites-available/your-project-name.conf) and add these lines before the WSGIScriptAlias line:
Alias /media/ /path/to/your/project/media/ <Directory /path/to/your/project/media/> Require all granted Options FollowSymLinks </Directory>
Replace /path/to/your/project/media/ with the actual absolute path to your media folder (e.g., /var/www/my-django-app/media/). This tells Apache to map requests to /media/ to your server's media directory.
Step 3: Fix File Permissions
Apache runs under the www-data user by default, so it needs read/write access to your media folder to serve existing files and save new uploads. Run these commands to set the correct permissions:
# Give Apache ownership of the media folder sudo chown -R www-data:www-data /path/to/your/project/media/ # Set readable/writable permissions sudo chmod -R 755 /path/to/your/project/media/
If you have subfolders inside media (like profile_pics or documents), these commands will apply to them too.
Step 4: Restart Apache to Apply Changes
After updating the config and permissions, restart Apache to make sure the changes take effect:
sudo systemctl restart apache2
Important Notes
- Never use
DEBUG=Truein production: WhenDEBUGis enabled, Django will serve media files itself, but this is only for development. For production, keepDEBUG=Falseand let Apache handle media serving. - Multipart forms: If your app allows file uploads, ensure your HTML forms include
enctype="multipart/form-data"—this is required for Django to process file uploads correctly. - Static files vs media files: Don’t confuse media files (user-uploaded content) with static files (CSS, JS, images bundled with your app). You’ll still need to run
python manage.py collectstaticto serve static files via Apache, but media files are handled separately as above.
内容的提问来源于stack exchange,提问作者Maninder Singh

