Django AWS S3: Host Static & Media Files
In this article
Yes, you can host Django static and media files on Amazon S3, and it is the standard approach for production deployments. By configuring Django's storage backends to use S3, you offload file serving from your web server, improve scalability, and ensure that user-uploaded media and static assets are stored durably. This article explains how it works, how to set it up, and what to watch out for.
Why Use S3 for Django Static and Media Files
In development, Django serves static files (CSS, JavaScript, images) and media files (user uploads) from your local filesystem. In production, relying on your application server for this is inefficient and fragile. S3 offers several benefits:
- Scalability: S3 handles massive traffic and storage without you managing servers.
- Performance: Files are served from Amazon's global edge network via CloudFront, reducing latency.
- Durability: S3 provides 99.999999999% durability, protecting against data loss.
- Separation: Your application server stays lean, focusing on dynamic requests.
- Cost: For most projects, S3 storage and transfer costs are lower than maintaining dedicated file servers.
How Django Storage Backends Work
Django's file storage system abstracts where files are saved. By default, it uses FileSystemStorage, which stores files on the local disk. To use S3, you replace this with a custom storage backend provided by the django-storages library. This library integrates with the boto3 AWS SDK to communicate with S3.
You configure two separate storages: one for static files (collected via collectstatic) and one for media files (user uploads). Each can have its own bucket or folder, permissions, and caching behavior.
Setting Up S3 for Django
Before touching code, you need an AWS account and an S3 bucket. Here’s a step-by-step overview:
- Create an S3 bucket in a region close to your users. Enable public access only if you want files to be publicly readable (common for static and media). For private files, block public access.
- Create an IAM user with programmatic access. Attach a policy that grants
s3:PutObject,s3:GetObject,s3:DeleteObject, ands3:ListBucketon your bucket. - Install packages:
pip install django-storages boto3 - Add to INSTALLED_APPS:
'storages' - Configure settings.py with your bucket name, access keys, and storage backends.
Example configuration:
# settings.py AWS_ACCESS_KEY_ID = 'your-access-key' AWS_SECRET_ACCESS_KEY = 'your-secret-key' AWS_STORAGE_BUCKET_NAME = 'my-django-bucket' AWS_S3_REGION_NAME = 'us-east-1' AWS_DEFAULT_ACL = 'public-read' AWS_QUERYSTRING_AUTH = False STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
For static files, you can also use a custom storage class to set a different folder:
# storage_backends.py
from storages.backends.s3boto3 import S3Boto3Storage
class StaticStorage(S3Boto3Storage):
location = 'static'
class MediaStorage(S3Boto3Storage):
location = 'media'Then point STATICFILES_STORAGE and DEFAULT_FILE_STORAGE to these classes.
Configuring Bucket Permissions and CORS
For public files, you must set the bucket policy to allow public read access. In the AWS console, add a bucket policy like:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::your-bucket-name/*"
}
]
}If you plan to upload files directly from the browser to S3 (common for large media), you need to configure CORS on the bucket. In the S3 console, add a CORS rule allowing your domain:
[
{
"AllowedHeaders": ["*"],
"AllowedMethods": ["GET", "PUT", "POST"],
"AllowedOrigins": ["https://yourdomain.com"],
"ExposeHeaders": []
}
]Common Issues and Troubleshooting
Even with correct setup, you may encounter these problems:
- 403 Forbidden: Usually means the IAM user lacks permissions or the bucket policy is wrong. Double-check the IAM policy and bucket policy.
- Files not showing up: If you use
collectstaticand files don't appear, ensureSTATICFILES_STORAGEis set correctly and that you runpython manage.py collectstaticafter deploying. - Slow uploads: For large files, consider using S3 direct uploads with presigned URLs to bypass your server.
- Private files being public: If you need private media, set
AWS_DEFAULT_ACL = 'private'and usedjango-storageswithquerystring_auth=Trueto generate temporary URLs. - Inconsistent behavior between local and production: Use environment variables for AWS credentials and bucket name to keep settings clean.
Cost Considerations
S3 pricing is based on storage used, number of requests, and data transfer out. For most Django projects, costs are minimal—often pennies per month for small sites. However, large media libraries can accumulate storage costs. You can reduce costs by:
- Using S3 lifecycle policies to move old files to cheaper storage classes (e.g., Glacier).
- Enabling CloudFront to reduce data transfer costs (CloudFront egress is cheaper than S3 direct egress).
- Compressing images and videos before upload.
AWS provides a pricing calculator to estimate costs based on your expected usage.
Alternatives to S3
While S3 is the most common choice, other object storage services work with Django:
- Google Cloud Storage: Similar to S3, with
django-storagessupport viagcloudbackend. - Azure Blob Storage: Microsoft's offering, also supported by
django-storages. - DigitalOcean Spaces: S3-compatible, often cheaper for small projects.
- MinIO: Self-hosted, S3-compatible, useful for development or private clouds.
The configuration for these is similar, but you'll need to adjust the backend class and endpoint URL.
Security Best Practices
When using S3 with Django, follow these security guidelines:
- Never hardcode AWS credentials in your code. Use environment variables or IAM roles (if deploying on EC2).
- Use IAM roles for EC2 instances instead of access keys when possible.
- For private files, always use presigned URLs or signed cookies, never expose direct S3 links.
- Enable S3 server-side encryption (SSE-S3 or SSE-KMS) for sensitive data.
- Regularly audit your bucket permissions to ensure no unintended public access.
Frequently Asked Questions
Do I need to use CloudFront with S3?
Not strictly, but CloudFront is recommended for production. It caches files at edge locations, reducing latency and S3 data transfer costs. You can integrate CloudFront by setting the AWS_S3_CUSTOM_DOMAIN to your CloudFront domain in Django settings.
How do I make uploaded files private?
Set AWS_DEFAULT_ACL = 'private' and AWS_QUERYSTRING_AUTH = True. Then, when you access a file via file.url, Django will generate a presigned URL that expires after a set time (default 3600 seconds).
What happens to my existing local files when I switch to S3?
They remain on your server. You need to manually upload them to S3, or write a management command to transfer them. The django-storages library doesn't automatically migrate existing files.
Can I use S3 for both static and media in development?
Yes, but it's not recommended for local development because it adds latency and costs. Instead, keep using local storage in development and switch to S3 in production via environment variables.
How do I serve files from a custom domain with S3?
You can configure a custom domain by setting up a CNAME to your S3 bucket (if the bucket name matches the domain) or by using CloudFront with an alternate domain name. Then set AWS_S3_CUSTOM_DOMAIN in Django.